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
'use strict'; // Listens for the app launching then creates the window chrome.app.runtime.onLaunched.addListener(function() { var width = 600; var height = 400; chrome.app.window.create('index.html', { id: 'main', bounds: { width: width, height: height, left: Math.round((screen.availWidth - width) / 2), top: Math.round((screen.availHeight - height)/2) } }); });
yogiekurniawan/JayaMekar-ChromeApp
app/scripts/main.js
JavaScript
mit
454
var lint = require('mocha-eslint'); var paths = [ 'src', ]; var options = { // Note: we saw timeouts with the 2000ms mocha timeout setting, // thus raised to 5000ms for eslint timeout: 5000, // Defaults to the global mocha `timeout` option }; // Run the tests lint(paths, options);
iulia0103/taste-of-code
linter.js
JavaScript
mit
293
var express = require('express'); var router = express.Router(); var fs = require('fs'); var instasync = require('instasync'); var helpers = instasync.helpers; var queries = helpers.queries; //set Content type router.use(function(req,res,next){ res.header("Content-Type", "text/html"); res.header("X-Frame-Options","DENY"); next(); }); router.param('room_name', function(req,res, next, room_name){ queries.getRoom(room_name).then(function(room){ if (!room){ var error = new Error("Room not found."); error.status = 404; throw error; } req.room = room; return req.db("rooms").where("room_id",'=',room.room_id).increment("visits", 1); }).then(function(){ next(); }).catch(function(err){ return next(err); }); }); router.get('/:room_name', function(req, res, next) { res.render('rooms/index', { title: 'InstaSync - '+req.room.room_name+"'s room!", room: req.room }, function(err,html){ //not sure this is needed if(err) { next(err); } else { res.end(html); } }); }); module.exports = router;
Mewte/InstaSync
web/routes/rooms.js
JavaScript
mit
1,039
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-6.5 14.75c0 .41-.34.75-.75.75s-.75-.34-.75-.75V14h-1v2.25c0 .41-.34.75-.75.75s-.75-.34-.75-.75V14h-1v3.75c0 .41-.34.75-.75.75S6 18.16 6 17.75V13.5c0-.55.45-1 1-1h4.5c.55 0 1 .45 1 1v4.25zM10.75 10H13V9h-1.5c-.28 0-.5-.22-.5-.5s.22-.5.5-.5H13V7h-2.25c-.41 0-.75-.34-.75-.75s.34-.75.75-.75h2.75c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-2.75c-.41 0-.75-.34-.75-.75s.34-.75.75-.75zM18 16c0 .55-.45 1-1 1h-2v.75c0 .41-.34.75-.75.75s-.75-.34-.75-.75V13.5c0-.55.45-1 1-1H17c.55 0 1 .45 1 1V16z" /><path d="M15 14h1.5v1.5H15z" /></React.Fragment> , 'ThreeMpRounded');
callemall/material-ui
packages/material-ui-icons/src/ThreeMpRounded.js
JavaScript
mit
773
/** * body-checker * A simple tool to protect your API against bad request parameters * * @param {Object} body request body * @param {Object} options configuration parmaters * @param {Function} cb callback function * */ var check = require('check-types'); module.exports = function(body, options, cb) { var valid_keys = Object.keys(options); // Ensure all passed params are legal for(var p in body) { if(valid_keys.indexOf(p) === -1) { return cb(new Error('Illegal parameter "' + p + '" provided')); } } for(var key in options) { // Check for Required if(options[key].required && !body[key]) { switch(options[key].type) { case 'number': case 'integer': if(check.zero(body[key])) break; default: return cb(new Error('Missing required parameter ' + key)); } } // Optional default handler if(!options[key].required && !body[key] && options[key].default) { body[key] = options[key].default; } if (check[options[key].type](body[key]) === false) { // Check types for all but "any" allow undefined properties when not required if (body[key] === undefined && !options[key].required) { // skip when key is not present and is not required } else { if(options[key].type !== 'any') { return cb(new Error('Expected "' + key + '" to be type ' + options[key].type + ', instead found ' + typeof body[key])); } } } } // All is good return cb(null, body); };
luceracloud/body-checker
index.js
JavaScript
mit
1,461
/* AngularJS v1.3.4 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function(p,d,C){'use strict';function v(r,h,g){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,c,b,f,y){function z(){k&&(g.cancel(k),k=null);l&&(l.$destroy(),l=null);m&&(k=g.leave(m),k.then(function(){k=null}),m=null)}function x(){var b=r.current&&r.current.locals;if(d.isDefined(b&&b.$template)){var b=a.$new(),f=r.current;m=y(b,function(b){g.enter(b,null,m||c).then(function(){!d.isDefined(t)||t&&!a.$eval(t)||h()});z()});l=f.scope=b;l.$emit("$viewContentLoaded"); l.$eval(w)}else z()}var l,m,k,t=b.autoscroll,w=b.onload||"";a.$on("$routeChangeSuccess",x);x()}}}function A(d,h,g){return{restrict:"ECA",priority:-400,link:function(a,c){var b=g.current,f=b.locals;c.html(f.$template);var y=d(c.contents());b.controller&&(f.$scope=a,f=h(b.controller,f),b.controllerAs&&(a[b.controllerAs]=f),c.data("$ngControllerController",f),c.children().data("$ngControllerController",f));y(a)}}}p=d.module("ngRoute",["ng"]).provider("$route",function(){function r(a,c){return d.extend(Object.create(a), c)}function h(a,d){var b=d.caseInsensitiveMatch,f={originalPath:a,regexp:a},g=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?\*])?/g,function(a,d,b,c){a="?"===c?c:null;c="*"===c?c:null;g.push({name:b,optional:!!a});d=d||"";return""+(a?"":d)+"(?:"+(a?d:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=new RegExp("^"+a+"$",b?"i":"");return f}var g={};this.when=function(a,c){var b=d.copy(c);d.isUndefined(b.reloadOnSearch)&&(b.reloadOnSearch=!0); d.isUndefined(b.caseInsensitiveMatch)&&(b.caseInsensitiveMatch=this.caseInsensitiveMatch);g[a]=d.extend(b,a&&h(a,b));if(a){var f="/"==a[a.length-1]?a.substr(0,a.length-1):a+"/";g[f]=d.extend({redirectTo:a},h(f,b))}return this};this.caseInsensitiveMatch=!1;this.otherwise=function(a){"string"===typeof a&&(a={redirectTo:a});this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$templateRequest","$sce",function(a,c,b,f,h,p,x){function l(b){var e=s.current; (v=(n=k())&&e&&n.$$route===e.$$route&&d.equals(n.pathParams,e.pathParams)&&!n.reloadOnSearch&&!w)||!e&&!n||a.$broadcast("$routeChangeStart",n,e).defaultPrevented&&b&&b.preventDefault()}function m(){var u=s.current,e=n;if(v)u.params=e.params,d.copy(u.params,b),a.$broadcast("$routeUpdate",u);else if(e||u)w=!1,(s.current=e)&&e.redirectTo&&(d.isString(e.redirectTo)?c.path(t(e.redirectTo,e.params)).search(e.params).replace():c.url(e.redirectTo(e.pathParams,c.path(),c.search())).replace()),f.when(e).then(function(){if(e){var a= d.extend({},e.resolve),b,c;d.forEach(a,function(b,e){a[e]=d.isString(b)?h.get(b):h.invoke(b,null,null,e)});d.isDefined(b=e.template)?d.isFunction(b)&&(b=b(e.params)):d.isDefined(c=e.templateUrl)&&(d.isFunction(c)&&(c=c(e.params)),c=x.getTrustedResourceUrl(c),d.isDefined(c)&&(e.loadedTemplateUrl=c,b=p(c)));d.isDefined(b)&&(a.$template=b);return f.all(a)}}).then(function(c){e==s.current&&(e&&(e.locals=c,d.copy(e.params,b)),a.$broadcast("$routeChangeSuccess",e,u))},function(b){e==s.current&&a.$broadcast("$routeChangeError", e,u,b)})}function k(){var a,b;d.forEach(g,function(f,g){var q;if(q=!b){var h=c.path();q=f.keys;var l={};if(f.regexp)if(h=f.regexp.exec(h)){for(var k=1,m=h.length;k<m;++k){var n=q[k-1],p=h[k];n&&p&&(l[n.name]=p)}q=l}else q=null;else q=null;q=a=q}q&&(b=r(f,{params:d.extend({},c.search(),a),pathParams:a}),b.$$route=f)});return b||g[null]&&r(g[null],{params:{},pathParams:{}})}function t(a,b){var c=[];d.forEach((a||"").split(":"),function(a,d){if(0===d)c.push(a);else{var f=a.match(/(\w+)(?:[?*])?(.*)/), g=f[1];c.push(b[g]);c.push(f[2]||"");delete b[g]}});return c.join("")}var w=!1,n,v,s={routes:g,reload:function(){w=!0;a.$evalAsync(function(){l();m()})},updateParams:function(a){if(this.current&&this.current.$$route){var b={},f=this;d.forEach(Object.keys(a),function(c){f.current.pathParams[c]||(b[c]=a[c])});a=d.extend({},this.current.params,a);c.path(t(this.current.$$route.originalPath,a));c.search(d.extend({},c.search(),b))}else throw B("norout");}};a.$on("$locationChangeStart",l);a.$on("$locationChangeSuccess", m);return s}]});var B=d.$$minErr("ngRoute");p.provider("$routeParams",function(){this.$get=function(){return{}}});p.directive("ngView",v);p.directive("ngView",A);v.$inject=["$route","$anchorScroll","$animate"];A.$inject=["$compile","$controller","$route"]})(window,window.angular);
lisavogtsf/backbeat_website
vendor/angular-route.min.js
JavaScript
mit
4,479
'use strict'; /* Services */ angular.module('nhsApp.services', []) .config(function($httpProvider){ delete $httpProvider.defaults.headers.common['X-Requested-With']; }) .factory('nhsApiService', function($http) { var nhsAPI = {}; nhsAPI.getLetters = function() { return $http({ method: 'POST', url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/atoz.json" }); }; nhsAPI.getLetter = function(letter) { return $http({ method: 'POST', url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/atoz/"+ letter + ".json" }); }; nhsAPI.getCondition = function(condition) { return $http({ method: 'GET', url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/"+ condition + ".json" }); }; nhsAPI.getDetail = function(condition, detail) { return $http({ method: 'GET', url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/" + condition + "/" + detail + ".html" }); }; /* Useful to avoid all the extra mark-up in the Html version */ nhsAPI.getXmlDetail = function(condition, detail) { return $http({ method: 'GET', url: "../atozservice.php?requrl=http://v1.syndication.nhschoices.nhs.uk/conditions/articles/" + condition + "/" + detail + ".xml" }); }; return nhsAPI; });
denniskenny/Nhs-Choices-Angular
app/js/services.js
JavaScript
mit
1,529
export { default } from 'ember-disqus/components/disqus-comment-count';
sir-dunxalot/ember-disqus
app/components/disqus-comment-count.js
JavaScript
mit
71
/* @flow */ require('./sharedMocks'); jest.mock('glob', () => ({ sync: jest.fn(() => ['path/to/main/entry.js']), })); jest.mock('fs-extra'); // $FlowIgnore const entries = require('entries.json'); const buildEntries = require('../buildEntries'); const defaultGSConfig = require('../../defaults/glueStickConfig'); const generate = require('gluestick-generators').default; describe('config/webpack/buildEntries', () => { afterEach(() => { jest.resetAllMocks(); }); it('should build all client entries', () => { // $FlowIgnore expect(buildEntries(defaultGSConfig, {}, entries, [])).toEqual({ main: `./${defaultGSConfig.clientEntryInitPath}/main`, home: `./${defaultGSConfig.clientEntryInitPath}/home`, }); // $FlowIgnore expect(generate.mock.calls[0][0]).toEqual({ generatorName: 'clientEntryInit', entityName: 'main', options: { component: 'path/to/main/component', routes: 'path/to/main/routes', reducers: 'path/to/main/reducers', config: `${defaultGSConfig.configPath}/${defaultGSConfig.applicationConfigPath}`, clientEntryInitPath: defaultGSConfig.clientEntryInitPath, plugins: [], enableErrorOverlay: true, }, }); // $FlowIgnore expect(generate.mock.calls[1][0]).toEqual({ generatorName: 'clientEntryInit', entityName: 'home', options: { component: 'path/to/home/component', routes: 'path/to/home/routes', reducers: 'path/to/home/reducers', config: 'path/to/home/config', clientEntryInitPath: defaultGSConfig.clientEntryInitPath, plugins: [], enableErrorOverlay: true, }, }); }); it('should build only a signle client entry', () => { const homeEntry = Object.keys(entries) .filter(k => k === '/home') .reduce((acc, key) => ({ ...acc, [key]: entries[key] }), {}); // $FlowIgnore expect(buildEntries(defaultGSConfig, {}, homeEntry, [])).toEqual({ home: `./${defaultGSConfig.clientEntryInitPath}/home`, }); // $FlowIgnore expect(generate.mock.calls[0][0]).toEqual({ generatorName: 'clientEntryInit', entityName: 'home', options: { component: 'path/to/home/component', routes: 'path/to/home/routes', reducers: 'path/to/home/reducers', config: 'path/to/home/config', clientEntryInitPath: defaultGSConfig.clientEntryInitPath, plugins: [], enableErrorOverlay: true, }, }); }); });
TrueCar/gluestick
packages/gluestick/src/config/webpack/__tests__/buildEntries.test.js
JavaScript
mit
2,533
/** * Created by peter on 9/19/16. */ // ==UserScript== // @name Super Rookie // @namespace http://v.numag.net/grease/ // @description locate new posts on piratebay // @include https://thepiratebay.org/top/* // ==/UserScript== (function () { function $x() { var x=''; var node=document; var type=0; var fix=true; var i=0; var cur; function toArray(xp) { var final=[], next; while (next=xp.iterateNext()) { final.push(next); } return final; } while (cur=arguments[i++]) { switch (typeof cur) { case "string": x+=(x=='') ? cur : " | " + cur; continue; case "number": type=cur; continue; case "object": node=cur; continue; case "boolean": fix=cur; continue; } } if (fix) { if (type==6) type=4; if (type==7) type=5; } // selection mistake helper if (!/^\//.test(x)) x="//"+x; // context mistake helper if (node!=document && !/^\./.test(x)) x="."+x; var result=document.evaluate(x, node, null, type, null); if (fix) { // automatically return special type switch (type) { case 1: return result.numberValue; case 2: return result.stringValue; case 3: return result.booleanValue; case 8: case 9: return result.singleNodeValue; } } return fix ? toArray(result) : result; }; $x("/html/body/div[@id='main-content']/table[@id='searchResult']/tbody/tr/td[2]/a").map(function (element) { if (localStorage.getItem(element.href) == undefined){ localStorage.setItem(element.href,1); element.parentNode.style= 'background: darkorange;'; } else { localStorage.setItem(element.href,parseInt(localStorage.getItem(element.href))+1); }; }); })();
motord/elbowgrease
grease/superrookie.user.js
JavaScript
mit
2,103
/* @flow */ const babelJest = require('babel-jest'); module.exports = babelJest.createTransformer({ presets: [ [ 'env', { targets: { ie: 11, edge: 14, firefox: 45, chrome: 49, safari: 10, node: '6.11', }, modules: 'commonjs', }, ], 'react', ], plugins: [ 'transform-flow-strip-types', 'transform-class-properties', 'transform-object-rest-spread', ], });
boldr/boldr-ui
internal/jest/transform.js
JavaScript
mit
489
/** * Created by gkarak on 28/7/2016. */ 'use strict'; var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var lodash = require('lodash'); var prompts = require('../../services/prompts'); var buildContext = require('../../services/build-context'); var pathNames = require('../../services/path-names'); var append = require('../../services/append'); module.exports = yeoman.Base.extend({ prompting: function () { this.log('Generating ' + chalk.red('model') + ' for mongoose and api endpoints'); return this.prompt(this.options.objectName ? [] : prompts.angularObjectPrompts(this)) .then(function (props) { this.props = props; }.bind(this)); }, saveConfig: function () { this.config.set('objectName', this.props.objectName); this.config.set('objectTitle', this.props.objectTitle); this.config.set('objectUrl', this.props.objectUrl); }, writing: function () { var templatePaths = [ 'models/_object-name_.js.ejs', 'routes/api/_object-name_s.js.ejs' ]; if (this.options.objectName) lodash.extend(this.props, this.options); var context = buildContext({ objectName: this.props.objectName, objectTitle: this.props.objectTitle }); var $this = this; templatePaths.forEach(function (templatePath) { $this.fs.copyTpl( $this.templatePath(templatePath), $this.destinationPath(pathNames(templatePath, $this.props)), context ); }); // Modify files: append model route to express app var templatePath = 'app.js'; this.fs.copy( this.destinationPath(templatePath), this.destinationPath(templatePath), { process: function (content) { return append.expressRoute(content, $this.props.objectName, $this.props.objectTitle, $this.props.objectUrl); } }); // Modify files: append model require to mongoose service templatePath = this.destinationPath('services', 'mongoose.js'); this.fs.copy(templatePath, templatePath, { process: function (content) { return append.mongoose(content, $this.props.objectUrl); } }); } });
Wtower/generator-makrina
generators/model/index.js
JavaScript
mit
2,151
(function ($) { var theForm; var theBox; var theTypeTarget; var settings; $.fn.tagbox = function(options) { var defaults = { typeTargetNameAndId : "type_target", tagInputsArrayName : "tag_list", includeExampleTag : true }; settings = $.extend(defaults, options); theBox = this; theForm = theBox.parents("form"); theTypeTarget = setupTypeTarget(); setupTypeTargetKeyPressHandling(); setupExampleTagElement(); setupSimulatedFocus(); setupDimissTagListener(); return this; }; /** * */ function setupExampleTagElement(){ if(settings.includeExampleTag){ var exampleTagElement = $(buildExampleTagElement()); theBox.prepend(exampleTagElement); } } /** * When the fake textarea is clicked, pass focus to the hidden text-field. * Also, bind to the focus and blur events of the text-field to update the * fake textarea appearance, hence simulating focus */ function setupSimulatedFocus(){ theBox.click(function(event){ theTypeTarget.focus(); }); theTypeTarget.focus(function(event){ theBox.addClass("has_focus"); }); theTypeTarget.blur(function(event){ theBox.removeClass("has_focus"); }); } /** * */ function setupTypeTarget(){ var typeTarget = $(buildTypeTarget()); theBox.append(typeTarget); return typeTarget; } /** * */ function setupTypeTargetKeyPressHandling(){ //handle input: create tag if key==(enter, tab, comma, space), adjust width theTypeTarget.keydown(function(event){ var key = event.which if (key === 13 || key === 9 || key === 44 || key === 188 || key === 32){ event.preventDefault(); verifyAndCreateTag(); } else adjustTypeTargetWidth(); }); //adjust width on keyup as well, to cover any case (crossbrowser) theTypeTarget.keyup(function(event){ adjustTypeTargetWidth(); }); } /** * */ function setupDimissTagListener() { theBox.on("click", ".tag_element > .tag_dismiss", null, function(event){ event.preventDefault(); var theTagElement = $(this).parent(); removeTagElementAndHiddenInput(theTagElement); }); } /** * to adjust the hidden input's width */ function adjustTypeTargetWidth() { var len = theTypeTarget.val().length; theTypeTarget.css("width", len*11); if(parseInt(theTypeTarget.css("width")) < 40){ theTypeTarget.css("width", "40px") } } /** * if something has been typed in the input, create a new tag */ function verifyAndCreateTag() { var text = theTypeTarget.val(); if(text.length > 0) insertTagElement(text); } /** * */ function insertTagElement(text) { var jq_newTag = $(buildTagHtmlString(text)); jq_newTag.insertBefore(theTypeTarget); // resetting the input theTypeTarget.val("").css("width", "60px"); insertTagHiddenField(text); } /** * */ function insertTagHiddenField(text) { jq_newField = $(buildHiddenInputHtmlString(text)); theForm.prepend(jq_newField); } /** * builds the html string for the tag element */ function buildTagHtmlString(text) { var tag_str = "<div class='tag_element'><span class='tag_label'>" + text + "</span><a href='#' title='remove' class='tag_dismiss'>&times;</a></div>"; return tag_str; } /** * builds the html string for a hidden form input */ function buildHiddenInputHtmlString(text) { var input_str = '<input name="' + settings.tagInputsArrayName + '[]" type="hidden" value="' + text + '">'; return input_str; } /** * */ function removeTagElementAndHiddenInput(jq_tag){ var tagName = jq_tag.find(".tag_label").html(); // remove the tag from the tag box jq_tag.remove(); // remove the hidden input var sel = '[value="' + tagName + '"]'; $(sel).remove(); } /** * builds the html string for the example tag */ function buildExampleTagElement() { var tagStr = '<div class="tag_element"><span class="tag_label">example</span><a href="#" title="remove" class="tag_dismiss">&times;</a></div>'; return tagStr; } /** * builds the html string for the example tag */ function buildTypeTarget() { var tagStr = '<input name="' + settings.typeTargetNameAndId + '" id="' + settings.typeTargetNameAndId + '" type="text" maxlength="40">'; return tagStr; } }(jQuery)); // -- DEPRECATED /** * adds the tag string to the "chained" hidden input (if used) * I'm using "$%" to separate entries. I'll parse and split the string server-side */ // function addNewTagToHiddenStringField(text) { // var jq_tagsFormInput = $("#tag_list"); // var new_value = jq_tagsFormInput.val() + text + "$%"; // jq_tagsFormInput.val(new_value); // } /** * removes the tag string from the "chained" hidden input (if used) */ // function removeDeletedTagFromHiddenStringField(text) { // var jq_tagsFormInput = $("#tag_list"); // var originalValue = jq_tagsFormInput.val(); // var pattern = text + "$%"; // var newValue = originalValue.replace(pattern, ""); // jq_tagsFormInput.val(newValue); // }
tompave/tagbox
scripts/tagbox.js
JavaScript
mit
5,917
'use strict'; var _interopRequireDefault = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; exports.__esModule = true; var _core = require('core-js'); var _core2 = _interopRequireDefault(_core); var _hyphenate = require('./util'); var _bindingMode = require('aurelia-binding'); function getObserver(behavior, instance, name) { var lookup = instance.__observers__; if (lookup === undefined) { lookup = behavior.observerLocator.getObserversLookup(instance); behavior.ensurePropertiesDefined(instance, lookup); } return lookup[name]; } var BindableProperty = (function () { function BindableProperty(nameOrConfig) { _classCallCheck(this, BindableProperty); if (typeof nameOrConfig === 'string') { this.name = nameOrConfig; } else { Object.assign(this, nameOrConfig); } this.attribute = this.attribute || _hyphenate.hyphenate(this.name); this.defaultBindingMode = this.defaultBindingMode || _bindingMode.bindingMode.oneWay; this.changeHandler = this.changeHandler || null; this.owner = null; } BindableProperty.prototype.registerWith = function registerWith(target, behavior, descriptor) { behavior.properties.push(this); behavior.attributes[this.attribute] = this; this.owner = behavior; if (descriptor) { this.descriptor = descriptor; return this.configureDescriptor(behavior, descriptor); } }; BindableProperty.prototype.configureDescriptor = function configureDescriptor(behavior, descriptor) { var name = this.name; descriptor.configurable = true; descriptor.enumerable = true; if ('initializer' in descriptor) { this.defaultValue = descriptor.initializer; delete descriptor.initializer; delete descriptor.writable; } if ('value' in descriptor) { this.defaultValue = descriptor.value; delete descriptor.value; delete descriptor.writable; } descriptor.get = function () { return getObserver(behavior, this, name).getValue(); }; descriptor.set = function (value) { getObserver(behavior, this, name).setValue(value); }; return descriptor; }; BindableProperty.prototype.defineOn = function defineOn(target, behavior) { var name = this.name, handlerName; if (this.changeHandler === null) { handlerName = name + 'Changed'; if (handlerName in target.prototype) { this.changeHandler = handlerName; } } if (!this.descriptor) { Object.defineProperty(target.prototype, name, this.configureDescriptor(behavior, {})); } }; BindableProperty.prototype.createObserver = function createObserver(executionContext) { var _this = this; var selfSubscriber = null, defaultValue = this.defaultValue, initialValue; if (this.hasOptions) { return; } if (this.changeHandler !== null) { selfSubscriber = function (newValue, oldValue) { return executionContext[_this.changeHandler](newValue, oldValue); }; } if (defaultValue !== undefined) { initialValue = typeof defaultValue === 'function' ? defaultValue.call(executionContext) : defaultValue; } return new BehaviorPropertyObserver(this.owner.taskQueue, executionContext, this.name, selfSubscriber, initialValue); }; BindableProperty.prototype.initialize = function initialize(executionContext, observerLookup, attributes, behaviorHandlesBind, boundProperties) { var selfSubscriber, observer, attribute, defaultValue = this.defaultValue; if (this.isDynamic) { for (var key in attributes) { this.createDynamicProperty(executionContext, observerLookup, behaviorHandlesBind, key, attributes[key], boundProperties); } } else if (!this.hasOptions) { observer = observerLookup[this.name]; if (attributes !== undefined) { selfSubscriber = observer.selfSubscriber; attribute = attributes[this.attribute]; if (behaviorHandlesBind) { observer.selfSubscriber = null; } if (typeof attribute === 'string') { executionContext[this.name] = attribute; observer.call(); } else if (attribute) { boundProperties.push({ observer: observer, binding: attribute.createBinding(executionContext) }); } else if (defaultValue !== undefined) { observer.call(); } observer.selfSubscriber = selfSubscriber; } observer.publishing = true; } }; BindableProperty.prototype.createDynamicProperty = function createDynamicProperty(executionContext, observerLookup, behaviorHandlesBind, name, attribute, boundProperties) { var changeHandlerName = name + 'Changed', selfSubscriber = null, observer, info; if (changeHandlerName in executionContext) { selfSubscriber = function (newValue, oldValue) { return executionContext[changeHandlerName](newValue, oldValue); }; } else if ('dynamicPropertyChanged' in executionContext) { selfSubscriber = function (newValue, oldValue) { return executionContext.dynamicPropertyChanged(name, newValue, oldValue); }; } observer = observerLookup[name] = new BehaviorPropertyObserver(this.owner.taskQueue, executionContext, name, selfSubscriber); Object.defineProperty(executionContext, name, { configurable: true, enumerable: true, get: observer.getValue.bind(observer), set: observer.setValue.bind(observer) }); if (behaviorHandlesBind) { observer.selfSubscriber = null; } if (typeof attribute === 'string') { executionContext[name] = attribute; observer.call(); } else if (attribute) { info = { observer: observer, binding: attribute.createBinding(executionContext) }; boundProperties.push(info); } observer.publishing = true; observer.selfSubscriber = selfSubscriber; }; return BindableProperty; })(); exports.BindableProperty = BindableProperty; var BehaviorPropertyObserver = (function () { function BehaviorPropertyObserver(taskQueue, obj, propertyName, selfSubscriber, initialValue) { _classCallCheck(this, BehaviorPropertyObserver); this.taskQueue = taskQueue; this.obj = obj; this.propertyName = propertyName; this.callbacks = []; this.notqueued = true; this.publishing = false; this.selfSubscriber = selfSubscriber; this.currentValue = this.oldValue = initialValue; } BehaviorPropertyObserver.prototype.getValue = function getValue() { return this.currentValue; }; BehaviorPropertyObserver.prototype.setValue = function setValue(newValue) { var oldValue = this.currentValue; if (oldValue != newValue) { if (this.publishing && this.notqueued) { this.notqueued = false; this.taskQueue.queueMicroTask(this); } this.oldValue = oldValue; this.currentValue = newValue; } }; BehaviorPropertyObserver.prototype.call = function call() { var callbacks = this.callbacks, i = callbacks.length, oldValue = this.oldValue, newValue = this.currentValue; this.notqueued = true; if (newValue != oldValue) { if (this.selfSubscriber !== null) { this.selfSubscriber(newValue, oldValue); } while (i--) { callbacks[i](newValue, oldValue); } this.oldValue = newValue; } }; BehaviorPropertyObserver.prototype.subscribe = function subscribe(callback) { var callbacks = this.callbacks; callbacks.push(callback); return function () { callbacks.splice(callbacks.indexOf(callback), 1); }; }; return BehaviorPropertyObserver; })();
AMGTestOrg/templating
dist/commonjs/bindable-property.js
JavaScript
mit
7,942
const BaseXform = require('../base-xform'); /** https://en.wikipedia.org/wiki/Office_Open_XML_file_formats#DrawingML */ const EMU_PER_PIXEL_AT_96_DPI = 9525; class ExtXform extends BaseXform { constructor(options) { super(); this.tag = options.tag; this.map = {}; } render(xmlStream, model) { xmlStream.openNode(this.tag); const width = Math.floor(model.width * EMU_PER_PIXEL_AT_96_DPI); const height = Math.floor(model.height * EMU_PER_PIXEL_AT_96_DPI); xmlStream.addAttribute('cx', width); xmlStream.addAttribute('cy', height); xmlStream.closeNode(); } parseOpen(node) { if (node.name === this.tag) { this.model = { width: parseInt(node.attributes.cx || '0', 10) / EMU_PER_PIXEL_AT_96_DPI, height: parseInt(node.attributes.cy || '0', 10) / EMU_PER_PIXEL_AT_96_DPI, }; return true; } return false; } parseText(/* text */) {} parseClose(/* name */) { return false; } } module.exports = ExtXform;
guyonroche/exceljs
lib/xlsx/xform/drawing/ext-xform.js
JavaScript
mit
1,011
const test = require('ava') const { convert, convertWithMap } = require('../helper/spec') test('(convert) it works for an anonymous module', assert => { assert.truthy(convert('amdjs-api/anonymous-module')) }) test('(convert) it works for a dependency free module', assert => { assert.truthy(convert('amdjs-api/dependency-free-module')) }) test('(convert) it works for named module', assert => { assert.truthy(convert('amdjs-api/named-module')) }) test('(convert) it works for named module with arrow function', assert => { assert.truthy(convert('amdjs-api/named-module-arrow-fn')) }) test('(convert) it works for simple define statements', assert => { assert.truthy(convert('rjs-examples/simple-define')) }) test('(convert) it works for named dependencies', assert => { assert.truthy(convert('rjs-examples/function-wrapping')) }) test('(convert) it converts empty array in define correctly', assert => { assert.truthy(convert('define/callback-empty-array')) }) test('(convert) it converts empty array in define with array function correctly', assert => { assert.truthy(convert('define/arrow-function-callback-empty-array')) }) test('(convert) it converts define with callback only correctly using the built in parser', assert => { assert.truthy(convert('define/callback-only')) }) test('(convert) it converts empty define with arrow function correctly', assert => { assert.truthy(convert('define/arrow-function-callback-only')) }) test('(convert) it converts define with deps correctly', assert => { assert.truthy(convert('define/arrow-function-callback-with-deps')) }) test('(convert) it converts define with arrow function with immediate return', assert => { assert.truthy(convert('define/arrow-function-immediate-return')) }) test('(convert) it converts define with arrow function with immediate function return', assert => { assert.truthy(convert('define/arrow-function-immediate-return-function')) }) test('(convert) it converts define with deps with arrow function correctly', assert => { assert.truthy(convert('define/callback-with-deps')) }) test('(convert) it converts modules wrapped with iife correctly', assert => { assert.truthy(convert('define/iife')) }) test('(convert) it converts quotes correctly', assert => { assert.truthy(convert('define/quotes')) }) test.skip('(convert) it converts single quotes correctly', assert => { assert.truthy(convert('quotes/single', { quotes: 'single' })) }) test.skip('(convert) it converts double quotes correctly', assert => { assert.truthy(convert('quotes/double', { quotes: 'double' })) }) test('(convert) it converts auto quotes correctly', assert => { assert.truthy(convert('quotes/auto', { quotes: 'auto' })) }) test('(convert) it converts define with an object in callback only correctly', assert => { assert.truthy(convert('define/object-only')) }) test("(convert) it shouldn't convert files with no define", assert => { assert.truthy(convert('define/no-define')) }) test('(convert) it converts define with unused deps correctly', assert => { assert.truthy(convert('define/callback-with-mismatch-deps')) }) test('(convert) it keeps dependencies with side effects (behavior 1)', assert => { assert.truthy(convert('app/behavior_1')) }) test('(convert) it keeps dependencies with side effects (behavior 2)', assert => { assert.truthy(convert('app/behavior_2')) }) test('(convert) it converts controllers correctly', assert => { assert.truthy(convert('app/controller_1')) }) test('(convert) it keeps dependencies with side effects (controller 2)', assert => { assert.truthy(convert('app/controller_2')) }) test('(convert) it works with const', assert => { assert.truthy(convert('app/controller_3')) }) test('(convert) it works with let', assert => { assert.truthy(convert('app/controller_4')) }) test('(convert) it keeps custom object assignments', assert => { assert.truthy(convert('app/enum_1')) }) test('(convert) it leaves empty var statements (helper 1)', assert => { assert.truthy(convert('app/helper_1')) }) test('(convert) it leaves empty var statements (helper 2)', assert => { assert.truthy(convert('app/helper_2')) }) test('(convert) it works for named dependencies (helper 3)', assert => { assert.truthy(convert('app/helper_3')) }) test('(convert) it leaves empty var statements (model 1)', assert => { assert.truthy(convert('app/model_1')) }) test('(convert) it handles returns of objects', assert => { assert.truthy(convert('app/model_2')) }) test('(convert) it converts views correctly', assert => { assert.truthy(convert('app/view_1')) }) test('(convert) it converts modules with functions after the return correctly', assert => { assert.truthy(convert('app/view_2')) }) test('(convert) it converts modules with constructors assigned to variables correctly', assert => { assert.truthy(convert('app/view_3')) }) test('(convert) it handles a var declaration which is moved to a separate line', assert => { assert.truthy(convert('app/view_4')) }) test('(convert) it drops an empty define', assert => { assert.truthy(convert('app/view_spec_1')) }) test('(convert) it converts subapps correctly', assert => { assert.truthy(convert('app/subapp_1')) }) test('(convert) it converts subapp specs correctly', assert => { assert.truthy(convert('app/subapp_spec_1', { quotes: 'double' })) }) test('(convert) it converts modules with one require sugar call expression correctly', assert => { assert.truthy(convert('app/module_1')) }) test('(convert) it converts modules with multiple require sugar call expressions correctly', assert => { assert.truthy(convert('app/module_2')) }) test('(convert) it converts module specs correctly', assert => { assert.truthy(convert('app/module_spec_1')) }) test('(convert) it converts troopjs components correctly (troopjs 1)', assert => { assert.truthy(convert('web-examples/troopjs_component_1')) }) test('(convert) it converts troopjs components correctly (troopjs 2)', assert => { assert.truthy(convert('web-examples/troopjs_component_2')) }) test('(convert) it converts require sugar correctly', assert => { assert.truthy(convert('define/require-sugar')) }) test('(convert) it converts require sugar proxy correctly', assert => { assert.truthy(convert('define/require-sugar-proxy')) }) test('(convert) it converts require sugar proxy with member expression correctly', assert => { assert.truthy(convert('define/require-sugar-proxy-inline')) }) test('(convert) it converts require sugar proxy with nested member expressions correctly', assert => { assert.truthy(convert('define/require-sugar-proxy-inline-nested')) }) test('(convert) it converts require sugar with side effects correctly', assert => { assert.truthy(convert('define/require-sugar-with-side-effect')) }) test('(convert) it converts require with property assignment correctly', assert => { assert.truthy(convert('define/require-sugar-with-property-assignment')) }) test('(convert) it converts todomvc backbone requirejs example correctly (backbone 1)', assert => { assert.truthy(convert('web-examples/todomvc_backbone_requirejs_1')) }) test('(convert) it converts todomvc backbone requirejs example correctly (backbone 2)', assert => { assert.truthy(convert('web-examples/todomvc_backbone_requirejs_2')) }) test('(convert) it converts todomvc backbone requirejs example correctly (backbone 3)', assert => { assert.truthy(convert('web-examples/todomvc_backbone_requirejs_3')) }) test('(convert) it converts todomvc angular requirejs example correctly (angular 1)', assert => { assert.truthy(convert('web-examples/todomvc_angularjs_requirejs_1')) }) test('(convert) it converts todomvc angular requirejs example correctly (angular 2)', assert => { assert.truthy(convert('web-examples/todomvc_angularjs_requirejs_2')) }) test('(convert) it converts todomvc angular requirejs example correctly (angular 3)', assert => { assert.truthy(convert('web-examples/todomvc_angularjs_requirejs_3')) }) test('(convert) it converts todomvc knockout requirejs example correctly', assert => { assert.truthy(convert('web-examples/todomvc_knockout_requirejs_1')) }) test('(convert) it converts todomvc lavaca requirejs example correctly', assert => { assert.truthy(convert('web-examples/todomvc_lavaca_requirejs_1')) }) test('(convert) it converts todomvc somajs requirejs example correctly (soma 1)', assert => { assert.truthy(convert('web-examples/todomvc_somajs_requirejs_1')) }) test('(convert) it converts todomvc somajs requirejs example correctly (soma 2)', assert => { assert.truthy(convert('web-examples/todomvc_somajs_requirejs_2')) }) test('(convert) it returns sourcemaps', assert => { assert.truthy(convertWithMap('source-maps/unnamed', { sourceMap: true })) }) test('(convert) it handles destructuring', assert => { assert.truthy(convert('define/destructuring')) }) test('(convert) it handles destructuring for multiple keys', assert => { assert.truthy(convert('define/destructuring-multiple-keys')) }) test('(convert) it handles destructuring for named keys', assert => { assert.truthy(convert('define/destructuring-named-keys')) }) test('(convert) it handles destructuring for require sugar', assert => { assert.truthy(convert('define/require-sugar-destructuring')) }) test('(convert) it handles destructuring for require sugar with many variables', assert => { assert.truthy(convert('define/require-sugar-destructuring-many-variables')) }) test('(convert) it works for simplified commonjs wrapping', assert => { assert.truthy(convert('amdjs-api/simplified-commonjs-wrapping')) }) test('(convert) it works for simplified commonjs wrapping that returns a literal', assert => { assert.truthy(convert('amdjs-api/simplified-commonjs-wrapping-returns-literal')) }) test('(convert) it works for named simplified commonjs wrapping', assert => { assert.truthy(convert('amdjs-api/named-simplified-commonjs-wrapping')) }) test('(convert) it works for named simplified commonjs wrapping with sugar', assert => { assert.truthy(convert('amdjs-api/named-simplified-commonjs-wrapping-with-sugar')) }) test('(convert) it works for named simplified commonjs wrapping with sugar (2)', assert => { assert.truthy(convert('amdjs-api/named-simplified-commonjs-wrapping-with-sugar-second')) }) test('(convert) it handles anonymous imports', assert => { assert.truthy(convert('define/imports-anonymous')) }) test('(convert) it converts exports.default correctly', assert => { assert.truthy(convert('define/exports-default')) }) test('(convert) it removes code that defines the __esModule property', assert => { assert.truthy(convert('define/exports-object-define-property')) }) test('(convert) it does not remove code that defines other properties', assert => { assert.truthy(convert('define/exports-object-define-property-keep')) }) test('(convert) it handles multiple exports assignments to undefined', assert => { assert.truthy(convert('define/exports-overrides')) }) test('(convert) it handles exports with same names', assert => { assert.truthy(convert('define/exports-same')) }) test('(convert) it handles multiple exports assignments', assert => { assert.truthy(convert('define/exports-multiple')) }) test('(convert) it handles exports with condition', assert => { assert.truthy(convert('define/exports-with-condition')) }) test('(convert) it handles exports with condition and multiple overrides', assert => { assert.truthy(convert('define/exports-with-condition-and-overrides')) }) test('(convert) it works for multiple returns', assert => { assert.truthy(convert('define/multiple-returns')) }) test('(convert) it is a noop for files with dynamic imports', assert => { assert.truthy(convert('noop/dynamic-import')) }) test('(convert) it does not break on files with dynamic import', assert => { assert.truthy(convert('define/dynamic-import')) }) test('(convert) it does not break on files with async await', assert => { assert.truthy(convert('define/async-await')) }) test('(convert) it does not create multiple default exports', assert => { assert.truthy(convert('define/if-statement-and-exports-default')) }) test.skip('(convert) it handles optional chaining', assert => { assert.truthy(convert('define/optional-chaining')) }) test.skip('it leaves single line comments if required', assert => { assert.truthy(convert('define/single-line-comments', { comments: true })) }) test.skip('it leaves multi line comments if required', assert => { assert.truthy(convert('define/multi-line-comments', { comments: true })) }) test.skip('it leaves single line comments in code if required', assert => { assert.truthy(convert('define/comments', { comments: true })) }) test.skip('it handles jsx', assert => { assert.truthy(convert('jsx/react', { jsx: true })) })
buxlabs/buxlabs.amd-to-es6
test/spec/convert.js
JavaScript
mit
12,870
import angular from "angular"; import DefinitionCreatorComponent from "./definitionCreator.component"; let DefinitionCreatorModule = angular.module("DefinitionCreatorModule", []) .directive("sgDefinitionCreatorModal", DefinitionCreatorComponent); export default DefinitionCreatorModule;
booknds/sge
src/app/components/modals/definitionCreator/definitionCreator.js
JavaScript
mit
321
/// <reference path="../Interfaces/IDisposable.ts" /> /// <reference path="../Interfaces/ITyped.ts" /> /// <reference path="LooperCallback.ts" />
NTaylorMullen/EndGate
EndGate/EndGate.Core.JS/Loopers/ILooper.js
JavaScript
mit
146
var class_predicate2_test = [ [ "SetUp", "class_predicate2_test.html#a9778563daf4846327d32061c1a8ccba0", null ], [ "TearDown", "class_predicate2_test.html#a7379f8f7772af6b4c76edcc90b6aaaeb", null ] ];
bhargavipatel/808X_VO
docs/html/class_predicate2_test.js
JavaScript
mit
208
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { d: "M5 19h14V5H5v14zm5-11l5 4-5 4V8z", opacity: ".3" }), h("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zM10 8v8l5-4z" })), 'SlideshowTwoTone');
AlloyTeam/Nuclear
components/icon/esm/slideshow-two-tone.js
JavaScript
mit
340
const debug = require('debug')('stuco:web:middleware:error') let errorCodes = { 'User Not Found': 0, 'Requesting User Not Found': 1, 'Event Not Found': 2, 'Invalid Location Data': 3, 'Google Token Validation Failed': 4, 'TokenIssuer is Invalid': 5, 'Invalid Token Certificate': 6, 'UserToken Has Expired': 7, 'Not At Event Location': 8, 'Already Checked Into Event': 9, 'Not During Event Time': 10, 'User File Empty': 11, 'Failed to Create User': 12, 'Invalid UserToken': 13, 'Permission Requirements Not Met': 14, 'Invalid Permission Type': 15, 'Badge Not Found': 16, 'DeprecationWarning': 17, 'Invalid Request Parameters': 18, 'Missing or Invalid Authentication Header': 19, 'Failed to Edit User': 20, 'Google Certificates Retrieval Error': 21, 'Certificate Parsing Error': 22, 'Invalid Email Domain': 23, 'Malformed UserToken': 24, 'Invalid API Key': 25, 'Unexpected Error': 26 } let error = (req, res, next) => { debug('initializing response error method') res.error = (error) => { debug('response error method called') if (error == null) { debug('assuming unxpected since error was null') error = 'Unexpected Error' } if (!(error instanceof Error)) { error = new Error(error.toString().replace(/(?:\r\n|\r|\n)/g, '').trim()) } return res.json({ error: error.message, errorid: errorCodes[error.message] == null ? -1 : errorCodes[error.message] }) } debug('initialized response error method') return next() } module.exports.inject = error module.exports.errorCodes = errorCodes
RSCodingClub/STUCO-Backend
web/middleware/error.js
JavaScript
mit
1,622
// RECEIVING USERNAME & PASSWORD DATA //var data = require('../public/js/data.json'); //var projects = require('../projects.json'); var global_datajson = require('../globaldata.json'); var models = require('../models'); // MAIN FUNCTION - RENDERS/SHOWS HTML exports.delMeal = function(req, res){ var type; var projectID = req.query.id; models.Project .find({"id": projectID}) .exec(before); function before (err, proj){ if (proj[0].color=='redish') { console.log('am here'); global_datajson[0].cheat_had = global_datajson[0].cheat_had-1; global_datajson[0].cheat_left = global_datajson[0].cheat_left+1 } } models.Project .find({"id": projectID}) .remove() .exec(afterRemove); function afterRemove (err, projects){ if(err) console.log(err); //res.send('ok'); } models.Project .find() .sort({"id":-1}) .exec( function before_renderProjects(err, projDB){ models.Project2 .find() .exec( function render2(err, cheats){ res.render('index', {"meal" : projDB, "total_cheat" : global_datajson[0].total_cheat, "cheat_left" : global_datajson[0].cheat_left, "cheat_had" : global_datajson[0].cheat_had}); }); }); }
srishtyagrawal/joy4-add1
routes/del.js
JavaScript
mit
1,176
'use strict'; angular.module('aqbClient', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngResource', 'ui.router', 'ui.bootstrap']); angular.module('aqbClient') .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: 'app/main/main.html', controller: 'MainCtrl' }); $urlRouterProvider.otherwise('/'); });
spaztick256/aquariumbuddy
client/src/app/index.js
JavaScript
mit
506
import React from 'react'; import Header from './Header'; import Copyright from './Copyright'; import PCHeader from './PCHeader'; class App extends React.Component { componentDidMount() { $("#back-to-top").headroom({ tolerance: 2, offset: 50, classes: { initial: "animated", pinned: "fadeIn", unpinned: "fadeOut" } }); } render() { return ( <view> <div className="web-pc-banner"></div> <div className="pc-container"> <PCHeader /> {this.props.children} <Copyright /> <ToolBar /> </div> </view> ); } } class ToolBar extends React.Component { /** <a href="javascript:;" className="toolbar-item toolbar-item-app"> <span className="toolbar-code-layer"> <div id="urlcode"></div> </span> </a> */ render() { return (<div className="toolbar"> <a href="javascript:;" className="toolbar-item toolbar-item-weixin"> <span className="toolbar-layer2"> <img src="images/limao.jpg" width="130" height="130"/> </span> </a> <a href="javascript:;" className="toolbar-item toolbar-item-feedback"> <span className="toolbar-layer3"> <img src="images/weixin/kf.jpg" width="130" height="130"/> </span> </a> <a href="javascript:scroll(0,0)" id="top" className="toolbar-item toolbar-item-top"></a> </div>) } } class BackTop extends React.Component { render() { return (<a href="javascript:scroll(0,0)" id="back-to-top" style= {{display: "inline"}}><i className="glyphicon glyphicon-chevron-up"></i></a>) } } export default App;
kongchun/BigData-Web
app/components/App.js
JavaScript
mit
1,790
$(document).ready(function() { CKEDITOR.replace("sl_content", { fullPage: true, allowedContent: true, filebrowserUploadUrl: '/ckeditor/upload' }); $(".poll_delete").click(function(){ if($("#poll_title li").length<=2) { alert('항목은 최소 두개는 입력되어야 합니다.') return false; } $(this).parent().remove(); }); $("#poll_add").click(function(){ $("#poll_title").append($("#poll_title li:last").clone(true)); }); });
sleeping-lion/slboard_codeigniter
public/js/boards/add.js
JavaScript
mit
481
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. "use strict";
webreed/webreed
test/fakes/plugins/fake-plugin-without-setup.js
JavaScript
mit
142
'use strict'; var path = require('path'); var test = require('ava'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); test.before(() => { return helpers.run(path.join(__dirname, '../../generators/gulp')) .withOptions({ 'skip-install': true, 'uploading': 'None' }) .toPromise(); }); test('creates html.js', () => { assert.file('gulp/tasks/html.js'); }); test('contains correct tasks', () => { assert.fileContent('gulp/tasks/html.js', 'gulp.task(\'html'); });
sondr3/generator-statisk
test/gulp/html.js
JavaScript
mit
519
function scrollDistanceFromBottom() { return pageHeight() - (window.pageYOffset + self.innerHeight); } function pageHeight() { return $("body").height(); }
bloopletech/pictures
public/javascripts/application.js
JavaScript
mit
160
/* global chrome */ (function contentScript() { function onPageMessage(event) { const message = event.data; if (event.source !== window) { return; } // Only accept messages that we know are ours if (typeof message !== 'object' || message === null || message.source !== 'react-rpm') { return; } // Ignore messages send from contentScript, avoid infinite dispatching if (message.sender === 'contentScript') { return; } chrome.runtime.sendMessage(message); } function onMessage(message, /* sender, sendResponse */) { // relay all messages to pageScript window.postMessage({ ...message, sender: 'contentScript' }, '*'); } window.addEventListener('message', onPageMessage); chrome.runtime.onMessage.addListener(onMessage); }());
mkawauchi/react-rpm
chrome/extension/content/contentScript.js
JavaScript
mit
814
'use strict'; const path = require('path'); const should = require('should'); const Nconfetti = require('./../../index.js'); describe('Nconfetti#loadSync', () => { it('should loadSync all config files of given directory', (done) => { const nconfetti = new Nconfetti({path: path.join(__dirname, '..', 'configs', 'env'), env: 'development'}); const config = nconfetti.loadSync(); const expectedConfig = { development_config: { development_config: 'A Entry', }, sub_folder: { sub_folder_config: { sub: 'A sub entry', }, }, }; should(config) .deepEqual(expectedConfig); done(); }); });
5minds/nconfetti
tests/nconfetti/test_load_sync.js
JavaScript
mit
684
#!/usr/bin/env node /* * rapò * https://github.com/leny/rapo * * JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner * * Copyright (c) 2014 Leny * Licensed under the MIT license. */ "use strict"; var chalk, error, pkg, program, rapo, sURL, spinner; pkg = require("../package.json"); rapo = require("./rapo.js"); chalk = require("chalk"); error = function(oError) { console.log(chalk.bold.red("✘ " + oError + ".")); return process.exit(1); }; (spinner = require("simple-spinner")).change_sequence(["◓", "◑", "◒", "◐"]); (program = require("commander")).version(pkg.version).usage("[options] <url>").description("Performance reviews for websites, using PhantomJS.").parse(process.argv); if (!(sURL = program.args[0])) { error("No URL given!"); } spinner.start(50); rapo(sURL, {}, function(oError, oResults) { spinner.stop(); console.log(oResults); return process.exit(0); });
leny/rapo
lib/cli.js
JavaScript
mit
937
/** * IP blocker extension for frontend HTTPD * * (C) 2021 TekMonks. All rights reserved. * License: See enclosed file. */ const utils = require(conf.libdir+"/utils.js"); let ipblacklist = []; exports.name = "ipblocker"; exports.initSync = _ => utils.watchFile(`${conf.confdir}/ipblacklist.json`, data=>ipblacklist=JSON.parse(data), conf.ipblacklistRefresh||10000); exports.processRequest = async (req, res, _dataSender, _errorSender, _access, error) => { if (_isBlacklistedIP(req)) { error.error(`Blocking blacklisted IP ${utils.getClientIP(req)}`); // blacklisted, won't honor res.socket.destroy(); res.end(); return true; } else return false; } function _isBlacklistedIP(req) { let clientIP = utils.getClientIP(req); if (req.socket.remoteFamily == "IPv6") clientIP = utils.getEmbeddedIPV4(clientIP)||utils.expandIPv6Address(clientIP);; return ipblacklist.includes(clientIP.toLowerCase()); }
TekMonks/monkshu
frontend/server/ext/ipblocker.js
JavaScript
mit
925
( function ( root, factory ) { if ( typeof define === 'function' && define.amd ) { define( [ 'ko' ], factory ); } else { root.router = factory( root.ko ); }; }( this, function ( ko ) { "use strict"; var router = { on404: function ( rt, e ) { throw new Error( [ 'Path' + router.resolvePath.apply( router, rt ) + ' not found.', 'You can handle the error by overriding this function.' ].join( '\n' ) ); }, route: ko.observableArray(), root: Page( { title: window.document.title } ), resolvePath: function resolvePath() { var args = Array.from( arguments ); var url = args.map( function ( r, i, s ) { if ( r.slice( -1 ) !== '/' && i !== s.length - 1 ) r += '/'; return r; } ).reduce( function ( url, path ) { return new window.URL( path, url.href ); }, new window.URL( window.location.origin ) ); return url.pathname + url.search + url.hash; }, navigate: function navigate( href ) { href = router.resolvePath( href ); return guards( path( href ) ).then( function () { window.history.pushState( {}, '', href ); router.route( path() ); } ); }, start: function start( opts ) { return ( window.onpopstate = handlePop )(); }, loader: { start: function () {}, done: function () {} } }; router.Page = Page; ko.bindingHandlers[ 'page' ] = { init: function ( element, valueAccessor, allBindingsAccessor, viewModel, bindingContext ) { var value = valueAccessor(); if ( !value.route ) throw new Error( 'route required' ); var parent = bindingContext._page || router.root; var page = parent.to[ value.route ] = parent.to[ value.route ] || Page( { route: value.route } ); Object.assign( page, { element: element, src: value.src, title: value.title || parent.title, template: value.template, guard: value.guard, onclose: value.onclose, context: bindingContext } ); page.close(); return { controlsDescendantBindings: true }; } }; ko.bindingHandlers[ 'nav' ] = { update: function ( element, valueAccessor, allBindingsAccessor, viewModel, bindingContext ) { var value = valueAccessor(); var page = bindingContext._page || {}; var route = page.path ? page.path() : '/'; if ( element.tagName === 'A' ) element.href = router.resolvePath( route, value ); element.onclick = function ( ev ) { var href = this.href || router.resolvePath( route, value ); if ( ev.button !== 0 || ( ev.ctrlKey && ev.button === 0 ) ) { if ( this.tagName !== 'A' ) window.open( href, '_blank' ).focus(); return true; }; router.navigate( href ); return false; }; } }; function Page( data ) { if ( !( this instanceof Page ) ) return new Page( data ); data = data || {}; this.element = data.element; this.route = data.route; this.title = data.title; this.template = data.template; this.guard = data.guard; this.onclose = data.onclose; this.current = ''; this.src = data.src; this.context = data.context; this.to = {}; }; Page.prototype.check = function check( route ) { return wrap( this.guard, this, [ route ] ).then( function () { return this; }.bind( this ) ); }; Page.prototype.ensureTemplate = function ensureTemplate() { var tmplname = this.template.name || this.template; var tmpl = window.document.querySelector( 'script#' + tmplname ); if ( !tmpl && !this.src ) return Promise.reject( new Error( 'No template or source supplied' ) ); if ( !tmpl && this.src ) return window.fetch( encodeURI( this.src ) ).then( function ( response ) { if ( response.status !== 200 ) { var e = new Error( response.statusText ); e.response = response; throw e; }; return response.text(); } ).then( function ( text ) { var tmpl = document.createElement( 'div' ); tmpl.innerHTML = text; tmpl = tmpl.firstChild; if ( !tmpl || tmpl.tagName !== 'SCRIPT' || tmpl.id !== tmplname ) throw new Error( 'Wrong source' ); window.document.body.appendChild( tmpl ); } ); }; Page.prototype.open = function open( current ) { this.current = current; if ( !this.template || !this.element ) return this; ko.applyBindingsToNode( this.element, { template: this.template }, this.context.extend( { _page: this } ) ); this.element.style.display = ''; return this; }; Page.prototype.close = function close() { this.current = ''; var children = Array.from( this.element.children ); var ready = Promise.resolve(); if ( children.length ) ready = wrap( this.onclose, this ); return ready.then( function () { children.map( function ( c ) { c.remove(); } ); this.element.style.display = 'none'; return this; }.bind( this ) ); }; Page.prototype.closeChildren = function closeChildren() { return Promise.all( Object.keys( this.to ).map( function ( t ) { return this.to[ t ].close(); }.bind( this ) ) ); }; Page.prototype.closeSiblings = function closeSiblings() { var parent = this.parent(); if ( !parent ) return; return Promise.all( Object.keys( parent.to ).map( function ( t ) { if ( parent.to[ t ] !== this ) return parent.to[ t ].close(); }.bind( this ) ) ); }; Page.prototype.next = function next( route ) { if ( !route && this.to[ '/' ] ) return this.to[ '/' ]; if ( route && this.to[ route ] ) return this.to[ route ]; if ( route && this.to[ '*' ] ) return this.to[ '*' ]; }; Page.prototype.path = function path() { var path = []; var parent = this; do { path.unshift( parent.current ); parent = parent.parent(); } while ( parent ) return path.join( '/' ); }; Page.prototype.parent = function parent() { if ( this === router.root ) return; try { return this.context._page || router.root; } catch ( e ) { return router.root; }; }; function guards( rt ) { router.loader.start(); console.log( 'GUARD', rt ); return router.root.check( rt ).then( workGuard.bind( this, { rt: Array.from( rt ), page: router.root } ) ).then( function ( page ) { window.document.title = page.title || router.root.title; router.loader.done(); return page; } ).catch( function ( e ) { if ( e instanceof Promise ) return e; if ( e instanceof Error && e.message === 'Page not found' ) return router.on404( rt, e ); throw e; router.loader.done(); } ); }; function workGuard( cur ) { var r = cur.rt.shift(); var next = cur.page.next( r ); if ( !next ) return cur.page.closeChildren().then( function () { if ( r ) return Promise.reject( new Error( 'Page not found' ) ); return Promise.resolve( cur.page ); }.bind( this ) ); return Promise.all( [ next.check( r ), next.ensureTemplate() ] ).then( function ( res ) { cur.page = res[ 0 ]; if ( cur.page.current === r ) return; return cur.page.closeSiblings().then( function () { cur.page.open( r ); } ); } ).then( workGuard.bind( this, cur ) ); }; function handlePop() { return guards( path() ).then( function () { router.route( path() ); } ); }; function path( pathname ) { return ( pathname || window.location.pathname ).slice( 1 ).split( '/' ).filter( function ( r ) { return !!r; } ); }; function wrap( target, reciever, args ) { if ( target instanceof Error ) return Promise.reject( target ); if ( !( target instanceof Function ) ) return Promise.resolve( target ); if ( !Array.isArray( args ) ) args = [ args ]; try { var r = ( reciever || args ) ? target.apply( reciever, args ) : target.call(); if ( !( r instanceof Promise ) ) return Promise.resolve( r ); return r; } catch ( e ) { return Promise.reject( e ); }; }; return router; } ) );
qwemaze/ko-router
ko-router.js
JavaScript
mit
9,328
const RATING_CHANGED = 'RATING_CHANGED'; const Rating = function(model, context) { var stars = []; for (var i = 1; i <= model.top; i++) { let star = model.rating < i ? '☆' : '★'; let prevRating = (model.rating == model.prevRating) ? '' : ` (was ${model.prevRating}/${model.top})`; let title = `${model.rating}/${model.top}${prevRating}`; let key = parseInt(i); stars.push( h('span', {onClick: ()=>context.bus$.push({type: RATING_CHANGED, rating: key}), key: i, title: title}, star) ); } return( h('div', null, [ h('p', {className: "event-form-rating"}, stars), h('input', {type: "hidden", name: "event[rating]", value: model.rating}, null) ]) ); } const RatingApplet = { view: Rating, update: function(message) { switch (message.type) { case RATING_CHANGED: this.updateModel({rating: message.rating}); break; } } } export default RatingApplet;
dncrht/mical
app/javascript/packs/rating.js
JavaScript
mit
948
'use strict'; var grunt = require('grunt'), config = require('./config'); exports.log = grunt.log; exports.verbose = grunt.verbose; exports.init = function() { if (!config.get('cool_colors')) { grunt.option('color', false); grunt.log.initColors(); } if (config.get('verbose')) { grunt.option('verbose', true); } };
jacobk/werk
lib/logger.js
JavaScript
mit
341
//= require ./templates/uploading //= require ./templates/complete //= require ./s3_fileupload
allen13/s3_fileupload_rails
app/assets/javascripts/s3_fileupload/index.js
JavaScript
mit
94
var five = require("johnny-five");<% if (projectType === "useParticle") { %> var Spark = require("spark-io"); var board = new five.Board({ // Create Johnny-Five board connected via Spark. // Assumes access tokens are stored as environment variables // but you can enter them directly below instead. io: new Spark({ token: <%- sparkToken ? '"' + sparkToken + '"': 'process.env.SPARK_TOKEN'; %>, deviceId: <%- sparkDeviceID ? '"' + sparkDeviceID + '"': 'process.env.SPARK_DEVICE_ID'; %> }) });<% } else if (projectType === "useRasPi") { %> var board = new five.Board({ io: new Raspi() }); <% } else { %> var board = new five.Board(); <% } if (includeBarcli) { %> var Barcli = require("barcli"); <% } if (includej5Songs) { %> var songs = require("j5-songs"); <% } if (includeNodePixel) { %> var pixel = require("node-pixel"); var strip = null; <% } if (includeOledJS) { %> var Oled = require("oled-js"); <% } %> // The board's pins will not be accessible until // the board has reported that it is ready board.on("ready", function () { console.log("Ready!"); <% if (includeBarcli) { %> // See https://github.com/dtex/barcli for usage var graph = new Barcli(); // Sets bar to 25% graph.update(0.25); // Sets bar to 100% graph.update(1.0); <% } if (includeOledJS) { %> //OLED Options var opts = { width: 128, height: 64, address: 0x3D }; // Instance of Oled var oled = new Oled(board, five, opts); // See https://github.com/noopkat/oled-js for usage. oled.clearDisplay(); <% } if (includeNodePixel) { %> // Node-Pixel options strip = new pixel.Strip({ data: 6, length: 4, firmata: board, controller: "FIRMATA", }); strip.on("ready", function () { // do stuff with the strip here. // See https://github.com/ajfisher/node-pixel for usage }); <% } if (includej5Songs) { %> // j5-songs var piezo = new five.Piezo(3); // Load a song object var song = songs.load("never-gonna-give-you-up"); // See https://github.com/julianduque/j5-songs for more songs and usage // Play it ! piezo.play(song); <% } if (!(includej5Songs || includeOledJS || includeNodePixel)) { if (projectType === "useParticle") { %> var led = new five.Led("D7"); <% } else {%> var led = new five.Led(13); <% } %> led.blink(500);<% } %> });
pierceray/generator-johnny-five
generators/app/templates/_index.js
JavaScript
mit
2,333
/** * Particle */ (function() { var nspace = this.Particle; /** * * @type Particle */ var Particle = nspace.Particle = function(spin, energy) { this.spin = spin; this.energy = energy; }; Particle.SPIN_HALF = 0.5; Particle.SPIN_ONE = 1; Particle.prototype = { spin: null, mass: null, restEnergy: null, charge: null, energy: null, /** * * @param {Number} energy * @return {Particle} */ setEnergy: function(energy) { this.energy = energy; return this; }, /** * * @return {Number} */ getEnergy: function() { return this.energy; }, /** * @returns {Number} */ getMass: function() { return this.mass; }, /** * @returns {Number} eV */ getRestEnergy: function() { return this.restEnergy; }, /** * @returns {Number} eV */ getCharge: function() { return this.charge; }, /** * @returns {Number} */ getSpin: function() { return this.spin; } }; })();
bjester/quantum-probability
lib/particle/Particle.js
JavaScript
mit
1,080
/** * A script that will read all users from one Auth0 tenant and create new users * in another Auth0 tenant. The existing users' metadata will be ready and only * those users with a matching datatools client_id will be copied over. The new * users will have new passwords set, so the users will have to reset their * passwords to regain access. * * Two config files are required for this to work. The `from-client.json` will * contain information for machine-to-machine connections and the existing * client application ID that users should have in their metadata. The * `to-client.json` file should have information for machine-to-machine * connections and the client application ID that will replace to old * applicaiton client ID in their metadata. * * If deleting (and then recreating) existing users in the to tenant is desired, * the connection ID is also required. A way to find the connection ID involves * going to the Auth0 API explorer, setting the API token with a token generated * from a machine-to-machine API for the to tenant and then executing the "Get * all connections" endpoint. * See here: https://auth0.com/docs/api/management/v2#!/Connections/get_connections. * That endpoint will give a listing of all connections. Find the connection * with the name "Username-Password-Authentication" and use that ID. * * Both of the `from-client.json` and `to-cleint.json` files should have the * following base format: * * { * "apiClient": "SECRET", * "apiSecret": "SECRET", * "domain": "SECRET.auth0.com", * "clientId": "SECRET" * "connectionId": "secrect" // optional in to-client.json for deleting users * } * * * To run the script, open a cli and type `node migrate-auth0-users.js` */ const fetch = require('isomorphic-fetch') const omit = require('lodash/omit') const qs = require('qs') const uuid = require('uuid/v4') // load required config files const from = require('./from-client.json') const to = require('./to-client.json') const DEFAULT_CONNECTION_NAME = 'Username-Password-Authentication' const deleteExistingUsersInToClient = true /** * Get a Management API token using machine-to-machine credentials. */ async function getManagementToken (connectionSettings) { const { apiClient, apiSecret, domain } = connectionSettings // make request to auth0 to get a token const token = await fetch( `https://${domain}/oauth/token`, { body: JSON.stringify({ grant_type: 'client_credentials', client_id: apiClient, client_secret: apiSecret, audience: `https://${domain}/api/v2/` }), headers: { 'content-type': 'application/json' }, method: 'POST' } ) .then((res) => res.json()) .then((json) => { if (!json.access_token) { // Encountered a problem authenticating with API, raise error console.error(json) throw new Error('error authenticating with Auth0 Management API') } else { // Authentication successful console.log(`received access to management api for domain ${domain}`) return json.access_token } }) return token } /** * Create header information to perform authenticated requests to management API */ function makeHeaderWithToken (token) { return { Authorization: `Bearer ${token}`, 'content-type': 'application/json' } } /** * Helper to wait for a bit * @param waitTime time in milliseconds */ function promiseTimeout (waitTime) { return new Promise((resolve, reject) => { setTimeout(resolve, waitTime) }) } /** * Delete a user from a tenant */ async function deleteUser (domain, token, connectionId, email) { // deleting a lot of users individually can sometimes result in 429 errors // from Auth0, so wait 4 seconds just in case. await promiseTimeout(4000) const response = await fetch( `https://${domain}/api/v2/connections/${connectionId}/users?${qs.stringify({email})}`, { headers: makeHeaderWithToken(token), method: 'DELETE' } ) if (response.status >= 400) { console.error(`Failed to delete user! Received status: ${response.status}`) console.error(await response.text()) } } /** * make request to create user */ async function createUser (domain, token, user) { const response = await fetch( `https://${domain}/api/v2/users`, { body: JSON.stringify(user), headers: makeHeaderWithToken(token), method: 'POST' } ) // check if request succeeded const createFailed = response.status >= 400 const responseJson = await response.json() if (createFailed) { // although the creation failed, don't raise an error as most // of the time this was caused by the user already existing console.error(`created user failed for ${user.email}`) return { responseJson, success: false } } else { // user creation successful! console.log(`created user ${user.email}`) return { success: true } } } async function main () { // get management tokens for both from and to tenants const fromToken = await getManagementToken(from) const toToken = await getManagementToken(to) // iterate through all users in from manager let numUsersFetched = 0 let totalUsers = Number.POSITIVE_INFINITY let page = 0 while (numUsersFetched < totalUsers) { // get a batch of 100 users (a limit imposed by auth0) const response = await fetch( `https://${from.domain}/api/v2/users?per_page=100&include_totals=true&page=${page}`, { headers: makeHeaderWithToken(fromToken) } ) const json = await response.json() // update the progress of fetching users numUsersFetched += json.users.length console.log(`fetched ${numUsersFetched} users so far`) totalUsers = json.total page++ // iterate through fetched users for (let user of json.users) { // only users that have a matching clientId should be created in the // new tenant, so assume they shouldn't be created until finding a // match let shouldCreateInNewApp = false // replace all user and app metadata with only the matching from // client data and then replace the client ID with the to client ID const metadatas = ['user_metadata', 'app_metadata'] metadatas.forEach(metadataKey => { if (!user[metadataKey]) return const metadata = user[metadataKey] if (!metadata.datatools) return metadata.datatools = metadata.datatools.filter( dt => dt.client_id === from.clientId ) if (metadata.datatools.length > 0) { shouldCreateInNewApp = true metadata.datatools[0].client_id = to.clientId } }) // no match found, continue to the next user in the current batch if (!shouldCreateInNewApp) continue // can't copy over passwords, so set the password of the copied user // as a UUID so that it's extremely unlikely for some random person // to guess the password. The user will have to reset their password // to gain access. user.password = uuid() // add required connection name (this is the default value created // by Auth0, so it could theoretically be different.) user.connection = DEFAULT_CONNECTION_NAME // omit items that will cause the creation to fail or cause weirdness // in new data values user = omit( user, [ 'logins_count', 'last_ip', 'last_login', 'last_password_reset', 'created_at', 'updated_at', 'identities' ] ) // Modify the user_id so an extra prefix isn't created. User IDs are in // the format `auth0|123456`. If that exact user ID is sent over as is // when creating the new user, the new user_id will look something like: // `auth0|auth0|123456`. If now user_id is included in the create user // request, then a completely new user_id is created. However, if a the // user_id is just the data beyond the "auth0|" (ie everything from // position 6 and beyond), then Auth0 will create a user_id with the // exact same data. user.user_id = user.user_id.substr(6) // attempt to create the user const createUserResult = await createUser(to.domain, toToken, user) if (!createUserResult.success) { // creation of user not successful, check if script should try again by // deleting an existing user if ( createUserResult.responseJson.message === 'The user already exists.' && deleteExistingUsersInToClient ) { // user creation failed due to existing user. Delete that existing // user and then try creating the user again console.log('Deleting existing user in to tenant') await deleteUser(to.domain, toToken, to.connectionId, user.email) const createUserResult2ndTry = await createUser(to.domain, toToken, user) if (!createUserResult2ndTry.success) { console.log('Creating user a 2nd time failed!') console.error(createUserResult.responseJson) } } else { console.error(createUserResult.responseJson) } } } } } main()
conveyal/datatools-manager
scripts/migrate-auth0-users.js
JavaScript
mit
9,303
'use strict'; const path = require('path'); const { config, paths, constants } = require('..'); test('config store is defined', () => { expect(config).toBeDefined(); }); test('config file default name', () => { expect(path.basename(config.path)).toEqual('config.json'); if (process.platform === "win32") { // https://github.com/sindresorhus/env-paths/blob/5944db4b2f8c635e8b39a363f6bdff40825be16e/index.js#L28 expect(path.basename(path.dirname(path.dirname(config.path)))).toEqual('DAISY Ace'); expect(path.basename(path.dirname(config.path))).toEqual('Config'); } else { expect(path.basename(path.dirname(config.path))).toEqual('DAISY Ace'); } }); test('paths are defined', () => { expect(paths).toBeDefined(); expect(paths.config).toBeDefined(); expect(paths.data).toBeDefined(); expect(paths.log).toBeDefined(); expect(paths.temp).toBeDefined(); }); test('constants are defined', () => { expect(constants).toBeDefined(); }); test('constants are as in constants.json', () => { expect(constants.dirname).toBe('DAISY Ace'); });
daisy/ace
packages/ace-config/src/__tests__/index.test.js
JavaScript
mit
1,074
var LocalStrategy = require('passport-local').Strategy; var User = require('../models/user.js'); var Rider = require('../models/rider.js'); module.exports = function(passport) { passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); passport.use('local', new LocalStrategy( function(username, password, done) { return User.validatePassword(username, password, done); })); passport.use('signup', new LocalStrategy({ passReqToCallback: true }, function(req, username, password, done) { User.findOne(username, done, function(err, user) { if (err) return done(err); if (user) return done(null, false, { message: req.flash('error', "That username is already taken") }); else { return User.create(req.body.realname, username, password, req.body.tel, req.body.type, done); } }); })); };
arodrig1/disgo
config/passport.js
JavaScript
mit
1,048
import * as React from 'react'; import * as ReactDOM from 'react-dom'; let Dial = React.createClass({ displayName: "Dial", _normalizeDegrees(degrees) { // Normalize to a positive value between 0 and 360 return (360 + degrees) % 360; }, _getDegrees() { return this._normalizeDegrees(this.props.degrees || this.state.degrees); }, _getRotation(factor=1) { // 45 gets the arrow to the top. return 'rotate(' + (factor * (this._getDegrees() + 45)) + 'deg)' }, _onMouseDown(evt) { // We are now moving this.setState({mouseDragging: true}); evt.preventDefault(); evt.stopImmediatePropagation(); }, _onMouseMove(evt) { if (!this.state.mouseDragging) { return; } let dialRect = this.refs.dialFace.getBoundingClientRect(); let mousePos = [evt.clientX, evt.clientY]; let dialPos = [dialRect.left + dialRect.width / 2, dialRect.top + dialRect.height / 2]; let radians = Math.atan2(dialPos[1] - mousePos[1], dialPos[0] - mousePos[0]); let degrees = radians * (180 / Math.PI) - 90; // Save it internally this.setState({degrees: degrees}); // Notify parent if (this.props.onChange) { this.props.onChange(this._normalizeDegrees(degrees)); } evt.preventDefault(); evt.stopImmediatePropagation(); }, _onMouseUp(evt) { if (!this.state.mouseDragging) { return; } // We are no longer moving this.setState({mouseDragging: false}); }, getInitialState() { return {mouseDragging: false, degrees: 0}; }, componentDidMount() { window.addEventListener("mouseup", this._onMouseUp); window.addEventListener("touchend", this._onMouseUp); window.addEventListener("mousemove", this._onMouseMove); window.addEventListener("touchmove", this._onMouseMove); }, componentWillUnmount() { window.removeEventListener("mouseup", this._onMouseUp); window.removeEventListener("mousemove", this._onMouseMove); window.removeEventListener("mousemove", this._onMouseMove); window.removeEventListener("touchmove", this._onMouseMove); }, render() { return <div className="dial" onMouseDown={this._onMouseDown} onTouchStart={this._onMouseDown}> <div className="dial__chamfer"> <div className="dial__face" style={{transform: this._getRotation()}} ref="dialFace"> <div className="dial__arrow"></div> <div className="dial__inner"></div> </div> </div> <div className="dial__text"> {this.props.children} &nbsp; {(Math.abs(this._getDegrees()) / 3.6).toFixed(0)}% </div> </div> } }); export {Dial};
staab/staab.github.io
src/js/components/features.js
JavaScript
mit
3,002
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; export default class App extends Component { static propTypes = { children: PropTypes.node, }; render() { return ( <div className="app"> <div className="main-container"> <div className="side-bar"> <h2><a href="https://github.com/supnate/rekit-example">Rekit Example</a></h2> <ul> <li><Link to="/rekit-example">Topic List</Link></li> <li><Link to="/rekit-example/topic/add">New Topic</Link></li> </ul> </div> <div className="page-container"> {this.props.children} </div> </div> </div> ); } }
supnate/rekit-example
src/containers/App.js
JavaScript
mit
747
define(['leaflet', 'layoutManager'], function(L, layoutManager) { return new (L.Class.extend({ initialize: function(options) { this.el = options.el; }, destroyModal: function() { this.modal = null; this.el.innerHTML = ''; }, setModal: function(modal) { this.destroyModal(); this.modal = modal; this.modal.appendTo(this.el); this.modal.on('destroy', function() { this.destroyModal(); }.bind(this)); } }))({ el: layoutManager.getModalsContainer() }) });
Pihta-Open-Data/TransportNocturnal
src/main/webapp/app/modalsManager.js
JavaScript
mit
631
import { coreUtils } from '../../' import fs from 'fs-extra' import path from 'path' export function editStructure(type, folderPath, oldFolderPath = null) { if (type === 'add') coreUtils.file.addFolder(folderPath) else if (type === 'rename') coreUtils.file.renameFolder(oldFolderPath, folderPath) else coreUtils.file.removeFolder(folderPath) return folderPath } export function list(dir) { const walk = entry => { return new Promise((resolve, reject) => { fs.exists(entry, exists => { if (!exists) { return resolve({}); } return resolve(new Promise((resolve, reject) => { fs.lstat(entry, (err, stats) => { if (err) { return reject(err); } if (!stats.isDirectory()) { return resolve({ title: path.basename(entry), key: path.basename(entry) }); } resolve(new Promise((resolve, reject) => { fs.readdir(entry, (err, files) => { if (err) { return reject(err); } Promise.all(files.map(child => walk(path.join(entry, child)))).then(children => { resolve({ title: path.basename(entry), key: path.basename(entry), folder: true, children: children }); }).catch(err => { reject(err); }); }); })); }); })); }); }); } return walk(dir); }
abecms/abecms
src/cli/cms/structure/structure.js
JavaScript
mit
1,631
/* * hasCommunityRole.js * Drew Nelson * Oct 21 2016 * * @module :: Policy Factory * @description :: Verifies the user has the passed role for the community or is an Admin of community * :: Also allows access if the user has a SuperUser role */ module.exports = function(role) { return function(req, res, next) { var roles = {SuperUser: 1, Admin: 2, Member: 3}; // set the search params to search for desired role or admin for community, or superuser access var criteria = { community: req.params.CommID, user: req.user.id, role: { in: [ roles[role], 1 ]} }; CommunityMember .find(criteria) .populate('role') .then(function(member) { if(member.length > 0) { // check to see if the user is a SU AND an Admin for the community // if so, pass the Admin role so the user doesn't get any SU warnings if(member[0].role.type == 'SuperUser' && (member[1] && member[1].role.type == 'Admin')) res.locals.role = member[1].role; else res.locals.role = member[0].role; return next(); } else return res.forbidden(); }); } }
dnelson23/smashtrack
app/api/policyFactories/hasCommunityRole.js
JavaScript
mit
1,081
/* --------------------------------------------------------------------------- WAIT! - This file depends on instructions from the PUBNUB Cloud. http://www.pubnub.com/account-javascript-api-include --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks Copyright (c) 2011 PubNub Inc. http://www.pubnub.com/ http://www.pubnub.com/terms --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------------- */ /* =-====================================================================-= */ /* =-====================================================================-= */ /* =-========================= JSON =============================-= */ /* =-====================================================================-= */ /* =-====================================================================-= */ (window['JSON'] && window['JSON']['stringify']) || (function () { window['JSON'] || (window['JSON'] = {}); if (typeof String.prototype.toJSON !== 'function') { String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON['stringify'] !== 'function') { JSON['stringify'] = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', {'': value}); }; } if (typeof JSON['parse'] !== 'function') { // JSON is parsed on the server for security. JSON['parse'] = function (text) {return eval('('+text+')')}; } }()); /* =-====================================================================-= */ /* =-====================================================================-= */ /* =-======================= DOM UTIL ===========================-= */ /* =-====================================================================-= */ /* =-====================================================================-= */ window['PUBNUB'] || (function() { /** * CONSOLE COMPATIBILITY */ window.console||(window.console=window.console||{}); console.log||(console.log=((window.opera||{}).postError||function(){})); /** * UTILITIES */ function unique() { return'x'+ ++NOW+''+(+new Date) } function rnow() { return+new Date } /** * LOCAL STORAGE OR COOKIE */ var db = (function(){ var ls = window['localStorage']; return { 'get' : function(key) { try { if (ls) return ls.getItem(key); if (document.cookie.indexOf(key) == -1) return null; return ((document.cookie||'').match( RegExp(key+'=([^;]+)') )||[])[1] || null; } catch(e) { return } }, 'set' : function( key, value ) { try { if (ls) return ls.setItem( key, value ) && 0; document.cookie = key + '=' + value + '; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/'; } catch(e) { return } } }; })(); /** * UTIL LOCALS */ var NOW = 1 , SWF = 'https://dh15atwfs066y.cloudfront.net/pubnub.swf' , REPL = /{([\w\-]+)}/g , ASYNC = 'async' , URLBIT = '/' , XHRTME = 310000 , SECOND = 1000 , PRESENCE_SUFFIX = '-pnpres' , UA = navigator.userAgent , XORIGN = UA.indexOf('MSIE 6') == -1; /** * NEXTORIGIN * ========== * var next_origin = nextorigin(); */ var nextorigin = (function() { var ori = Math.floor(Math.random() * 9) + 1; return function(origin) { return origin.indexOf('pubsub') > 0 && origin.replace( 'pubsub', 'ps' + (++ori < 10 ? ori : ori=1) ) || origin; } })(); /** * UPDATER * ====== * var timestamp = unique(); */ function updater( fun, rate ) { var timeout , last = 0 , runnit = function() { if (last + rate > rnow()) { clearTimeout(timeout); timeout = setTimeout( runnit, rate ); } else { last = rnow(); fun(); } }; return runnit; } /** * $ * = * var div = $('divid'); */ function $(id) { return document.getElementById(id) } /** * LOG * === * log('message'); */ function log(message) { console['log'](message) } /** * SEARCH * ====== * var elements = search('a div span'); */ function search( elements, start ) { var list = []; each( elements.split(/\s+/), function(el) { each( (start || document).getElementsByTagName(el), function(node) { list.push(node); } ); } ); return list; } /** * EACH * ==== * each( [1,2,3], function(item) { console.log(item) } ) */ function each( o, f ) { if ( !o || !f ) return; if ( typeof o[0] != 'undefined' ) for ( var i = 0, l = o.length; i < l; ) f.call( o[i], o[i], i++ ); else for ( var i in o ) o.hasOwnProperty && o.hasOwnProperty(i) && f.call( o[i], i, o[i] ); } /** * MAP * === * var list = map( [1,2,3], function(item) { return item + 1 } ) */ function map( list, fun ) { var fin = []; each( list || [], function( k, v ) { fin.push(fun( k, v )) } ); return fin; } /** * GREP * ==== * var list = grep( [1,2,3], function(item) { return item % 2 } ) */ function grep( list, fun ) { var fin = []; each( list || [], function(l) { fun(l) && fin.push(l) } ); return fin } /** * SUPPLANT * ======== * var text = supplant( 'Hello {name}!', { name : 'John' } ) */ function supplant( str, values ) { return str.replace( REPL, function( _, match ) { return values[match] || _ } ); } /** * BIND * ==== * bind( 'keydown', search('a')[0], function(element) { * console.log( element, '1st anchor' ) * } ); */ function bind( type, el, fun ) { each( type.split(','), function(etype) { var rapfun = function(e) { if (!e) e = window.event; if (!fun(e)) { e.cancelBubble = true; e.returnValue = false; e.preventDefault && e.preventDefault(); e.stopPropagation && e.stopPropagation(); } }; if ( el.addEventListener ) el.addEventListener( etype, rapfun, false ); else if ( el.attachEvent ) el.attachEvent( 'on' + etype, rapfun ); else el[ 'on' + etype ] = rapfun; } ); } /** * UNBIND * ====== * unbind( 'keydown', search('a')[0] ); */ function unbind( type, el, fun ) { if ( el.removeEventListener ) el.removeEventListener( type, false ); else if ( el.detachEvent ) el.detachEvent( 'on' + type, false ); else el[ 'on' + type ] = null; } /** * HEAD * ==== * head().appendChild(elm); */ function head() { return search('head')[0] } /** * ATTR * ==== * var attribute = attr( node, 'attribute' ); */ function attr( node, attribute, value ) { if (value) node.setAttribute( attribute, value ); else return node && node.getAttribute && node.getAttribute(attribute); } /** * CSS * === * var obj = create('div'); */ function css( element, styles ) { for (var style in styles) if (styles.hasOwnProperty(style)) try {element.style[style] = styles[style] + ( '|width|height|top|left|'.indexOf(style) > 0 && typeof styles[style] == 'number' ? 'px' : '' )}catch(e){} } /** * CREATE * ====== * var obj = create('div'); */ function create(element) { return document.createElement(element) } /** * timeout * ======= * timeout( function(){}, 100 ); */ function timeout( fun, wait ) { return setTimeout( fun, wait ); } /** * jsonp_cb * ======== * var callback = jsonp_cb(); */ function jsonp_cb() { return XORIGN || FDomainRequest() ? 0 : unique() } /** * ENCODE * ====== * var encoded_path = encode('path'); */ function encode(path) { return map( (encodeURIComponent(path)).split(''), function(chr) { return "-_.!~*'()".indexOf(chr) < 0 ? chr : "%"+chr.charCodeAt(0).toString(16).toUpperCase() } ).join(''); } /** * EVENTS * ====== * PUBNUB.events.bind( 'you-stepped-on-flower', function(message) { * // Do Stuff with message * } ); * * PUBNUB.events.fire( 'you-stepped-on-flower', "message-data" ); * PUBNUB.events.fire( 'you-stepped-on-flower', {message:"data"} ); * PUBNUB.events.fire( 'you-stepped-on-flower', [1,2,3] ); * */ var events = { 'list' : {}, 'unbind' : function( name ) { events.list[name] = [] }, 'bind' : function( name, fun ) { (events.list[name] = events.list[name] || []).push(fun); }, 'fire' : function( name, data ) { each( events.list[name] || [], function(fun) { fun(data) } ); } }; /** * XDR Cross Domain Request * ======================== * xdr({ * url : ['http://www.blah.com/url'], * success : function(response) {}, * fail : function() {} * }); */ function xdr( setup ) { if (XORIGN || FDomainRequest()) return ajax(setup); var script = create('script') , callback = setup.callback , id = unique() , finished = 0 , timer = timeout( function(){done(1)}, XHRTME ) , fail = setup.fail || function(){} , success = setup.success || function(){} , append = function() { head().appendChild(script); } , done = function( failed, response ) { if (finished) return; finished = 1; failed || success(response); script.onerror = null; clearTimeout(timer); timeout( function() { failed && fail(); var s = $(id) , p = s && s.parentNode; p && p.removeChild(s); }, SECOND ); }; window[callback] = function(response) { done( 0, response ); }; script[ASYNC] = ASYNC; script.onerror = function() { done(1) }; script.src = setup.url.join(URLBIT); if (setup.data) { script.src += "?"; for (key in setup.data) { script.src += key+"="+setup.data[key]+"&"; } } attr( script, 'id', id ); append(); return done; } /** * CORS XHR Request * ================ * xdr({ * url : ['http://www.blah.com/url'], * success : function(response) {}, * fail : function() {} * }); */ function ajax( setup ) { var xhr, response , finished = function() { if (loaded) return; loaded = 1; clearTimeout(timer); try { response = JSON['parse'](xhr.responseText); } catch (r) { return done(1); } success(response); } , complete = 0 , loaded = 0 , timer = timeout( function(){done(1)}, XHRTME ) , fail = setup.fail || function(){} , success = setup.success || function(){} , done = function(failed) { if (complete) return; complete = 1; clearTimeout(timer); if (xhr) { xhr.onerror = xhr.onload = null; xhr.abort && xhr.abort(); xhr = null; } failed && fail(); }; // Send try { xhr = FDomainRequest() || window.XDomainRequest && new XDomainRequest() || new XMLHttpRequest(); xhr.onerror = xhr.onabort = function(){ done(1) }; xhr.onload = xhr.onloadend = finished; xhr.timeout = XHRTME; url = setup.url.join(URLBIT); if (setup.data) { url += "?"; for (key in setup.data) { url += key+"="+setup.data[key]+"&"; } } xhr.open( 'GET', url, true ); xhr.send(); } catch(eee) { done(0); XORIGN = 0; return xdr(setup); } // Return 'done' return done; } /* =-====================================================================-= */ /* =-====================================================================-= */ /* =-========================= PUBNUB ===========================-= */ /* =-====================================================================-= */ /* =-====================================================================-= */ var PDIV = $('pubnub') || {} , READY = 0 , READY_BUFFER = [] , CREATE_PUBNUB = function(setup) { var CHANNELS = {} , PUBLISH_KEY = setup['publish_key'] || '' , SUBSCRIBE_KEY = setup['subscribe_key'] || '' , SSL = setup['ssl'] ? 's' : '' , UUID = setup['uuid'] || db.get(SUBSCRIBE_KEY+'uuid') || '' , ORIGIN = 'http'+SSL+'://'+(setup['origin']||'pubsub.pubnub.com') , SELF = { /* PUBNUB.history({ channel : 'my_chat_channel', limit : 100, callback : function(messages) { console.log(messages) } }); */ 'history' : function( args, callback ) { var callback = args['callback'] || callback , limit = args['limit'] || 100 , channel = args['channel'] , jsonp = jsonp_cb(); // Make sure we have a Channel if (!channel) return log('Missing Channel'); if (!callback) return log('Missing Callback'); // Send Message xdr({ callback : jsonp, url : [ ORIGIN, 'history', SUBSCRIBE_KEY, encode(channel), jsonp, limit ], success : function(response) { callback(response) }, fail : function(response) { log(response) } }); }, /* PUBNUB.time(function(time){ console.log(time) }); */ 'time' : function(callback) { var jsonp = jsonp_cb(); xdr({ callback : jsonp, url : [ORIGIN, 'time', jsonp], success : function(response) { callback(response[0]) }, fail : function() { callback(0) } }); }, /* PUBNUB.uuid(function(uuid) { console.log(uuid) }); */ 'uuid' : function(callback) { var u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); if (callback) callback(u); return u; }, /* PUBNUB.publish({ channel : 'my_chat_channel', message : 'hello!' }); */ 'publish' : function( args, callback ) { var callback = callback || args['callback'] || function(){} , message = args['message'] , channel = args['channel'] , jsonp = jsonp_cb() , url; if (!message) return log('Missing Message'); if (!channel) return log('Missing Channel'); if (!PUBLISH_KEY) return log('Missing Publish Key'); // If trying to send Object message = JSON['stringify'](message); // Create URL url = [ ORIGIN, 'publish', PUBLISH_KEY, SUBSCRIBE_KEY, 0, encode(channel), jsonp, encode(message) ]; // Send Message xdr({ callback : jsonp, success : function(response) { callback(response) }, fail : function() { callback([ 0, 'Disconnected' ]) }, url : url, data : { uuid: UUID } }); }, /* PUBNUB.unsubscribe({ channel : 'my_chat' }); */ 'unsubscribe' : function(args) { // Unsubscribe from both the Channel and the Presence Channel _unsubscribe(args['channel']); _unsubscribe(args['channel'] + PRESENCE_SUFFIX); function _unsubscribe(channel) { // Leave if there never was a channel. if (!(channel in CHANNELS)) return; // Disable Channel CHANNELS[channel].connected = 0; // Abort and Remove Script CHANNELS[channel].done && CHANNELS[channel].done(0); } }, /* PUBNUB.subscribe({ channel : 'my_chat' callback : function(message) { console.log(message) } }); */ 'subscribe' : function( args, callback ) { var channel = args['channel'] , callback = callback || args['callback'] , subscribe_key= args['subscribe_key'] || SUBSCRIBE_KEY , restore = args['restore'] , timetoken = 0 , error = args['error'] || function(){} , connect = args['connect'] || function(){} , reconnect = args['reconnect'] || function(){} , disconnect = args['disconnect'] || function(){} , presence = args['presence'] || function(){} , disconnected = 0 , connected = 0 , origin = nextorigin(ORIGIN); // Reduce Status Flicker if (!READY) return READY_BUFFER.push([ args, callback, SELF ]); // Make sure we have a Channel if (!channel) return log('Missing Channel'); if (!callback) return log('Missing Callback'); if (!SUBSCRIBE_KEY) return log('Missing Subscribe Key'); if (!(channel in CHANNELS)) CHANNELS[channel] = {}; // Make sure we have a Channel if (CHANNELS[channel].connected) return log('Already Connected'); CHANNELS[channel].connected = 1; // Recurse Subscribe function _connect() { var jsonp = jsonp_cb(); // Stop Connection if (!CHANNELS[channel].connected) return; // Connect to PubNub Subscribe Servers CHANNELS[channel].done = xdr({ callback : jsonp, url : [ origin, 'subscribe', subscribe_key, encode(channel), jsonp, timetoken ], data : { uuid: UUID }, fail : function() { // Disconnect if (!disconnected) { disconnected = 1; disconnect(); } timeout( _connect, SECOND ); SELF['time'](function(success){ // Reconnect if (success && disconnected) { disconnected = 0; reconnect(); } else { error(); } }); }, success : function(messages) { if (!CHANNELS[channel].connected) return; // Connect if (!connected) { connected = 1; connect(); } // Reconnect if (disconnected) { disconnected = 0; reconnect(); } // Restore Previous Connection Point if Needed // Also Update Timetoken restore = db.set( SUBSCRIBE_KEY + channel, timetoken = restore && db.get( subscribe_key + channel ) || messages[1] ); each( messages[0], function(msg) { callback( msg, messages ); } ); timeout( _connect, 10 ); } }); } // Presence Subscribe if (args['presence']) SELF.subscribe({ channel : args['channel'] + PRESENCE_SUFFIX, callback : presence, restore : args['restore'] }); // Begin Recursive Subscribe _connect(); }, 'here_now' : function( args, callback ) { var callback = args['callback'] || callback , channel = args['channel'] , jsonp = jsonp_cb() , origin = nextorigin(ORIGIN); // Make sure we have a Channel if (!channel) return log('Missing Channel'); if (!callback) return log('Missing Callback'); data = null; if (jsonp != '0') { data['callback']=jsonp; } // Send Message xdr({ callback : jsonp, url : [ origin, 'v2', 'presence', 'sub_key', SUBSCRIBE_KEY, 'channel', encode(channel) ], data: data, success : function(response) { callback(response) }, fail : function(response) { log(response) } }); }, // Expose PUBNUB Functions 'xdr' : xdr, 'ready' : ready, 'db' : db, 'each' : each, 'map' : map, 'css' : css, '$' : $, 'create' : create, 'bind' : bind, 'supplant' : supplant, 'head' : head, 'search' : search, 'attr' : attr, 'now' : rnow, 'unique' : unique, 'events' : events, 'updater' : updater, 'init' : CREATE_PUBNUB }; if (UUID == '') UUID = SELF.uuid(); db.set(SUBSCRIBE_KEY+'uuid', UUID); return SELF; }; // CREATE A PUBNUB GLOBAL OBJECT PUBNUB = CREATE_PUBNUB({ 'publish_key' : attr( PDIV, 'pub-key' ), 'subscribe_key' : attr( PDIV, 'sub-key' ), 'ssl' : attr( PDIV, 'ssl' ) == 'on', 'origin' : attr( PDIV, 'origin' ), 'uuid' : attr( PDIV, 'uuid' ) }); // PUBNUB Flash Socket css( PDIV, { 'position' : 'absolute', 'top' : -SECOND } ); if ('opera' in window || attr( PDIV, 'flash' )) PDIV['innerHTML'] = '<object id=pubnubs data=' + SWF + '><param name=movie value=' + SWF + '><param name=allowscriptaccess value=always></object>'; var pubnubs = $('pubnubs') || {}; // PUBNUB READY TO CONNECT function ready() { PUBNUB['time'](rnow); PUBNUB['time'](function(t){ timeout( function() { if (READY) return; READY = 1; each( READY_BUFFER, function(sub) { sub[2]['subscribe']( sub[0], sub[1] ) } ); }, SECOND ); }); } // Bind for PUBNUB Readiness to Subscribe bind( 'load', window, function(){ timeout( ready, 0 ) } ); // Create Interface for Opera Flash PUBNUB['rdx'] = function( id, data ) { if (!data) return FDomainRequest[id]['onerror'](); FDomainRequest[id]['responseText'] = unescape(data); FDomainRequest[id]['onload'](); }; function FDomainRequest() { if (!pubnubs['get']) return 0; var fdomainrequest = { 'id' : FDomainRequest['id']++, 'send' : function() {}, 'abort' : function() { fdomainrequest['id'] = {} }, 'open' : function( method, url ) { FDomainRequest[fdomainrequest['id']] = fdomainrequest; pubnubs['get']( fdomainrequest['id'], url ); } }; return fdomainrequest; } FDomainRequest['id'] = SECOND; // jQuery Interface window['jQuery'] && (window['jQuery']['PUBNUB'] = PUBNUB); // For Testling.js - http://testling.com/ typeof module !== 'undefined' && (module.exports = PUBNUB) && ready(); })();
cozza13/tipochat
core/3.2/pubnub-3.2.js
JavaScript
mit
29,957
import { StackNavigator, TabNavigator, TabBarBottom } from 'react-navigation' import ScheduleScreen from '../Containers/ScheduleScreen' import TalkDetailScreen from '../Containers/TalkDetailScreen' import BreakDetailScreen from '../Containers/BreakDetailScreen' import LocationScreen from '../Containers/LocationScreen' import AboutScreen from '../Containers/AboutScreen' import styles from './Styles/NavigationStyles' const ScheduleStack = StackNavigator({ Home: { screen: ScheduleScreen }, TalkDetail: { screen: TalkDetailScreen }, BreakDetail: { screen: BreakDetailScreen } }, { headerMode: 'none', initialRouteName: 'Home', cardStyle: styles.card }) const TabNav = TabNavigator({ Schedule: { screen: ScheduleStack }, Location: { screen: LocationScreen }, About: { screen: AboutScreen } }, { key: 'Schedule', tabBarComponent: TabBarBottom, tabBarPosition: 'bottom', animationEnabled: true, swipeEnabled: true, headerMode: 'none', initialRouteName: 'Schedule', tabBarOptions: { style: styles.tabBar, labelStyle: styles.tabBarLabel, activeTintColor: 'white', inactiveTintColor: 'white' } }) export default TabNav
infinitered/ChainReactApp
App/Navigation/AppNavigation.js
JavaScript
mit
1,169
describe("Conversion for", function() { describe("arffToJson", function() { it("convert arff file, basic types", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n@ATTRIBUTE see STRING\n\n@DATA\n1,3.5,do\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].bar).toBe(3.5); expect(json[0].see).toBe('do'); }); }); it("convert arff file, include carriage returns", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n1,3.5,do\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].bar).toBe(3.5); expect(json[0].see).toBe('do'); }); }); it("convert arff file, empty data", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n,2.0,saw\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(isNaN(json[0].foo)).toBe(true); expect(json[0].bar).toBe(2.0); expect(json[0].see).toBe('saw'); }); }); it("convert arff file, wrong type, numeric - string", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\nbleh,2.0,saw\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(isNaN(json[0].foo)).toBe(true); expect(json[0].bar).toBe(2.0); expect(json[0].see).toBe('saw'); }); }); it("convert arff file, wrong type, real - string", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n1,$,saw\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(isNaN(json[0].bar)).toBe(true); expect(json[0].see).toBe('saw'); }); }); it("convert arff file, wrong type, string - numeric", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n1,2.0,2\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].bar).toBe(2.0); expect(json[0].see).toBe('2'); }); }); it("convert arff file, missing data value", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n@ATTRIBUTE see STRING\n\n@DATA\n3.5,do\n2,2.5,while\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(2); expect(json[0].bar).toBe(2.5); expect(json[0].see).toBe('while'); expect(errors[0].message).toBe('data missing, not enough values to fill expected attributes'); }); }); it("convert arff file, basic types", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE class {lots,of,things}\n@ATTRIBUTE see STRING\n\n@DATA\n1,of,do\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].class).toBe('of'); expect(json[0].see).toBe('do'); }); }); it("convert arff file, carriage return", function() { //Given: var arff = "@RELATION iris\r@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE class {lots,of,things}\r\n@ATTRIBUTE see STRING\r\r@DATA\r1,of,do\r\r"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].class).toBe('of'); expect(json[0].see).toBe('do'); }); }); it("convert arff file, tabs in attributes", function() { //Given: var arff = "@RELATION iris\n@ATTRIBUTE foo REAL\n@ATTRIBUTE bar \t REAL\n@ATTRIBUTE joe \tREAL\n@ATTRIBUTE see\tREAL\n\n@DATA\n1.1,2.2,3.3,4.4\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1.1); expect(json[0].bar).toBe(2.2); expect(json[0].joe).toBe(3.3); expect(json[0].see).toBe(4.4); }); }); it("convert arff file, value wrapped in string", function() { //Given: var arff = "@RELATION iris\n@ATTRIBUTE foo REAL\n@ATTRIBUTE bar string\n\n@DATA\n1.1,do\n2.2,\'while\'\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1.1); expect(json[0].bar).toBe('do'); expect(json[1].foo).toBe(2.2); expect(json[1].bar).toBe('while'); }); }); }); });
ScottLogic/insight
tests/utils/Conversion.spec.js
JavaScript
mit
5,806
/** * @file This prototype manages all game entities. * * @author Human Interactive */ "use strict"; var GameEntity = require( "./GameEntity" ); var Player = require( "./Player" ); var Vehicle = require( "./Vehicle" ); /** * Creates the entity manager. * * @constructor */ function EntityManager() { Object.defineProperties( this, { entities : { value : [], configurable : false, enumerable : false, writable : false } } ); } /** * Creates the player object * * @param {World} world - The reference to the world object. * * @returns {Player} The new player. */ EntityManager.prototype.createPlayer = function( world ) { var player = new Player( world ); this.addEntity( player ); return player; }; /** * Creates a vehicle, a moving entity that uses steering behaviors. * * @param {World} world - The reference to the world object. * @param {THREE.Object3D} object3D - The 3D object of the entity. * @param {number} numSamplesForSmoothing - How many samples the smoother will use to average the velocity. * * @returns {Vehicle} The new vehicle. */ EntityManager.prototype.createVehicle = function( world, object3D, numSamplesForSmoothing ) { var vehicle = new Vehicle( world, object3D, numSamplesForSmoothing ); this.addEntity( vehicle ); return vehicle; }; /** * Updates all entities. * * @param {number} delta - The time delta value. */ EntityManager.prototype.update = function( delta ) { for ( var index = 0; index < this.entities.length; index++ ) { this.entities[ index ].update( delta ); } }; /** * Gets an entity by its ID. * * @param {number} id - The ID of the entity. * * @returns {GameEntity} The entity. */ EntityManager.prototype.getEntity = function( id ) { var entity = null; for ( var index = 0; index < this.entities.length; index++ ) { if ( this.entities[ index ].id === id ) { entity = this.entities[ index ]; break; } } if ( entity === null ) { throw "ERROR: EntityManager: Entity with ID " + id + " not existing."; } else { return entity; } }; /** * Adds a single entity to the internal array. * * @param {GameEntity} entity - The entity to add. */ EntityManager.prototype.addEntity = function( entity ) { this.entities.push( entity ); }; /** * Removes a single entity from the internal array. * * @param {GameEntity} entity - The entity to remove. */ EntityManager.prototype.removeEntity = function( entity ) { var index = this.entities.indexOf( entity ); this.entities.splice( index, 1 ); }; /** * Removes all entities from the internal array. * * @param {boolean} isClear - Should also all world entities be removed? */ EntityManager.prototype.removeEntities = function( isClear ) { if ( isClear === true ) { this.entities.length = 0; } else { for ( var index = this.entities.length - 1; index >= 0; index-- ) { // only remove entities with scope "STAGE" if ( this.entities[ index ].scope === GameEntity.SCOPE.STAGE ) { this.remove( this.children[ index ] ); } } } }; module.exports = new EntityManager();
Mugen87/yume
src/javascript/engine/game/entity/EntityManager.js
JavaScript
mit
3,096
Cliente = Backbone.Model.extend({ defaults: { empresa: 'Unknow', telefonos: [] }, initialize: function(attrs, opts){ } }); var cliente = new Cliente({nombre: 'Antonio', apellidos: 'García Ros'}); cliente.set({edad: 31, soltero: false}); alert(cliente.get('edad')); // 31
jesuscuesta/Backbone
02.- Modelos/07.- Model - modificando atributos/hello.js
JavaScript
mit
304
module.exports.up = async db => { await db.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); await db.raw('CREATE EXTENSION IF NOT EXISTS "hstore"'); await db.schema.createTable('role', table => { // pk table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('name', 64).notNullable().unique(); table.string('image', 200).nullable(); table.text('description').nullable(); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); // indexes table.index('name'); table.index('uuid'); }); await db.schema.createTable('user', table => { // pk table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('email', 100).unique().notNullable(); table.string('password', 64).notNullable(); table.string('firstName', 50).notNullable(); table.string('lastName', 50).notNullable(); table.string('username', 115).unique().notNullable(); table .string('avatarUrl', 255) .defaultTo('https://boldr.io/images/unknown-avatar.png'); table.string('profileImage', 255).nullable(); table.string('location', 100).nullable(); table.text('bio').nullable(); table.date('birthday', 8).nullable(); table.string('website', 100).nullable(); table.string('language', 10).notNullable().defaultTo('en_US'); table.json('social').nullable(); table.boolean('verified').defaultTo(false); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.timestamp('deletedAt').nullable().defaultTo(null); // fk // indexes table.index('username'); table.index('verified'); table.index('email'); }); await db.schema.createTable('verification_token', table => { // pk table.increments('id').unsigned().primary(); table.string('ip', 32); table.string('token'); table.boolean('used').defaultTo(false); table.uuid('userId').unsigned(); table.timestamp('createdAt').defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); // fk table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); // indexes table.index('token'); }); await db.schema.createTable('reset_token', table => { // pk table.increments('id').unsigned().primary(); table.string('ip', 32); table.string('token', 255).comment('hashed token'); table.dateTime('expiration'); table.boolean('used').defaultTo(false); table.uuid('userId').unsigned(); table.timestamp('createdAt').defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); // fk table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); // indexes table.index('token'); }); await db.schema.createTable('tag', table => { table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('name').notNullable().unique(); table.string('description').nullable(); table.index('name'); }); await db.schema.createTable('post', table => { // pk | uuid table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('title', 140).unique().notNullable(); table.string('slug', 140).unique().notNullable(); table.string('featureImage', 255).nullable(); table.json('attachments').nullable(); table.json('meta').nullable(); table.boolean('featured').defaultTo(false); table.json('rawContent'); table.text('content').notNullable(); table.text('excerpt').notNullable(); table.uuid('userId').unsigned().notNullable(); table.boolean('published').defaultTo(true); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.timestamp('deletedAt').nullable().defaultTo(null); // fk | uuid table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table.index('slug'); table.index('published'); table.index('createdAt'); }); await db.schema.createTable('attachment', table => { // pk | uuid table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('fileName').notNullable(); table.string('safeName').notNullable(); table.string('fileDescription'); table.string('fileType'); table.string('path'); table.uuid('userId').unsigned().notNullable(); table.string('url').notNullable(); table.timestamp('createdAt').defaultTo(db.fn.now()); table.timestamp('updatedAt').defaultTo(db.fn.now()); table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('setting', table => { table.increments('id').unsigned().primary(); table.string('key', 100).notNullable(); table.string('label', 100).notNullable(); table.string('value', 255).notNullable(); table.string('description', 255).notNullable(); table.index('key'); table.index('value'); }); await db.schema.createTable('menu', table => { table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('name').notNullable(); table.string('safeName').notNullable(); table.json('attributes').nullable(); table.boolean('restricted').default(false); table.index('safeName'); table.index('uuid'); }); await db.schema.createTable('menu_detail', table => { table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('safeName', 50).notNullable(); table.string('name', 50).notNullable(); table.string('cssClassname', 255).nullable(); table.boolean('hasDropdown').default(false); table.integer('order'); table .string('mobileHref', 255) .nullable() .comment( 'Mobile href is applicable in cases where the item is a dropdown' + 'trigger on desktop. Without a mobile href, it will only be text.'); // eslint-disable-line table.string('href').notNullable(); table.string('icon').nullable(); table.json('children'); table.index('safeName'); table.index('uuid'); table.index('href'); }); await db.schema.createTableIfNotExists('template', table => { table.increments('id').unsigned().primary(); table.uuid('uuid'); table.string('name', 100).unique().notNullable(); table.string('slug', 110).notNullable(); table.json('meta'); table.json('content'); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.index('slug'); table.index('uuid'); }); await db.schema.createTable('page', table => { table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('name').unique().notNullable(); table.string('slug').unique(); table.string('url').unique().notNullable(); table.json('layout'); table.json('data'); table.enu('status', ['published', 'draft', 'archived']).defaultTo('draft'); table.boolean('restricted').default(false); table.json('meta'); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.index('name'); }); await db.schema.createTable('activity', table => { table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.uuid('userId').unsigned().notNullable(); table.enu('type', ['create', 'update', 'delete', 'register']).notNullable(); table.uuid('activityPost').unsigned(); table.uuid('activityUser').unsigned(); table.uuid('activityAttachment').unsigned(); table.integer('activityTag').unsigned(); table.integer('activityMenuDetail').unsigned(); table.integer('activityTemplate').unsigned(); table.uuid('activityPage').unsigned(); table.integer('activityRole').unsigned(); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityPost') .references('id') .inTable('post') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityUser') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityAttachment') .references('id') .inTable('attachment') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityTag') .references('id') .inTable('tag') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityMenuDetail') .references('id') .inTable('menu_detail') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityTemplate') .references('id') .inTable('template') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityPage') .references('id') .inTable('page') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityRole') .references('id') .inTable('role') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('post_tag', table => { table.increments('id').primary(); table.uuid('postId').unsigned().notNullable(); table.integer('tagId').unsigned().notNullable(); table.unique(['postId', 'tagId']); table .foreign('postId') .references('id') .inTable('post') .onDelete('cascade') .onUpdate('cascade'); table .foreign('tagId') .references('id') .inTable('tag') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('user_role', table => { table.increments('id').primary(); table.uuid('userId').unsigned().notNullable(); table.integer('roleId').unsigned().notNullable(); table.unique(['userId', 'roleId']); table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table .foreign('roleId') .references('id') .inTable('role') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('template_page', table => { table.increments('id').primary(); table.uuid('pageId').unsigned().notNullable(); table.integer('templateId').unsigned().notNullable(); table.unique(['pageId', 'templateId']); table .foreign('pageId') .references('id') .inTable('page') .onDelete('cascade') .onUpdate('cascade'); table .foreign('templateId') .references('id') .inTable('template') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('menu_menu_detail', table => { table.integer('menuId').notNullable().references('id').inTable('menu'); table .integer('menuDetailId') .notNullable() .references('id') .inTable('menu_detail'); table.primary(['menuId', 'menuDetailId']); }); }; module.exports.down = async db => { await db.schema.dropTableIfExists('role'); await db.schema.dropTableIfExists('user'); await db.schema.dropTableIfExists('tag'); await db.schema.dropTableIfExists('post'); await db.schema.dropTableIfExists('attachment'); await db.schema.dropTableIfExists('setting'); await db.schema.dropTableIfExists('menu'); await db.schema.dropTableIfExists('menu_detail'); await db.schema.dropTableIfExists('template'); await db.schema.dropTableIfExists('page'); await db.schema.dropTableIfExists('activity'); await db.schema.dropTableIfExists('verification_token'); await db.schema.dropTableIfExists('reset_token'); await db.schema.dropTableIfExists('post_tag'); await db.schema.dropTableIfExists('user_role'); await db.schema.dropTableIfExists('template_page'); await db.schema.dropTableIfExists('menu_menu_detail'); }; module.exports.configuration = { transaction: true };
boldr/boldr-api
db/migrations/201701270219_initial.js
JavaScript
mit
12,958
/*! Drag Multiple Plugin - v0.1.2 - 2017-10-16 * https://github.com/javadoug/jquery.drag-multiple * Copyright (c) 2017 Doug Ross; Licensed MIT */ /*globals jQuery */ (function ($) { "use strict"; var options = { // allow consumer to specify the selection items: function getSelectedItems() { return $(".ui-draggable.ui-selected"); }, // allow consumer to cancel drag multiple beforeStart: function beforeDragMultipleStart() { // make sure target is selected, otherwise deselect others if (!(this.is('.ui-draggable') && this.is('.ui-selected'))) { $(".ui-draggable").removeClass('ui-selected'); return false; } }, // notify consumer of drag multiple beforeDrag: $.noop, // notify consumer of drag multiple stop beforeStop: $.noop, // multiple.stack stack: false }; function preventDraggableRevert() { return false; } /** given an instance return the options hash */ function initOptions(instance) { return $.extend({}, options, instance.options.multiple); } function callback(handler, element, jqEvent, ui) { if ($.isFunction(handler)) { return handler.call(element, jqEvent, ui); } } function notifyBeforeStart(element, options, jqEvent, ui) { return callback(options.beforeStart, element, jqEvent, ui); } function notifyBeforeDrag(element, options, jqEvent, ui) { return callback(options.beforeDrag, element, jqEvent, ui); } function notifyBeforeStop(element, options, jqEvent, ui) { return callback(options.beforeStop, element, jqEvent, ui); } $.ui.plugin.add("draggable", "multiple", { /** initialize the selected elements for dragging as a group */ start: function (ev, ui) { var element, instance, selected, options; // the draggable element under the mouse element = this; // the draggable instance instance = element.data('draggable') || element.data('ui-draggable'); // initialize state instance.multiple = {}; // the consumer provided option overrides options = instance.multiple.options = initOptions(instance); // the consumer provided selection selected = options.items(); // notify consumer before starting if (false === notifyBeforeStart(element, options, ev, ui)) { options.dragCanceled = true; return false; } // cache respective origins selected.each(function () { var position = $(this).position(); $(this).data('dragmultiple:originalPosition', $.extend({}, position)); }); // TODO: support the 'valid, invalid and function' values // currently only supports true // disable draggable revert, we will handle the revert instance.originalRevert = options.revert = instance.options.revert; instance.options.revert = preventDraggableRevert; // stack groups of elements // (adapted from jQuery UI 1.12.1-pre draggable) if (false !== options.stack) { var min, group; group = $.makeArray($(options.stack)).sort(function(a, b) { return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $( this ).css("zIndex", min + i); }); selected.each(function () { $(this).css("zIndex", min + group.length); }); } }, // move the selected draggables drag: function (ev, ui) { var element, instance, options; element = this; instance = element.data('draggable') || element.data('ui-draggable'); options = instance.multiple.options; if (options.dragCanceled) { return false; } notifyBeforeDrag(element, options, ev, ui); // check to see if consumer updated the revert option if (preventDraggableRevert !== instance.options.revert) { options.revert = instance.options.revert; instance.options.revert = preventDraggableRevert; } // TODO: make this as robust as draggable's positioning options.items().each(function () { var origPosition = $(this).data('dragmultiple:originalPosition'); // NOTE: this only works on elements that are already positionable $(this).css({ top: origPosition.top + (ui.position.top - ui.originalPosition.top), left: origPosition.left + (ui.position.left - ui.originalPosition.left) }); }); }, stop: function (ev, ui) { var element, instance, options; element = this; instance = element.data('draggable') || element.data('ui-draggable'); options = instance.multiple.options; if (options.dragCanceled) { return false; } notifyBeforeStop(element, options, ev, ui); // TODO: mimic the revert logic from draggable if (options.revert === true) { options.items().each(function () { var position = $(this).data('dragmultiple:originalPosition'); $(this).css(position); }); } // clean up options.items().each(function () { $(this).removeData('dragmultiple:originalPosition'); }); // restore orignal revert setting instance.options.revert = instance.originalRevert; } }); }(jQuery));
javadoug/jquery.drag-multiple
dist/jquery-ui.drag-multiple.js
JavaScript
mit
6,262
import GLBoost from '../../globals'; import GLBoostObject from '../core/GLBoostObject'; import GLExtensionsManager from '../core/GLExtensionsManager'; import MathClassUtil from '../../low_level/math/MathClassUtil'; import DrawKickerWorld from '../../middle_level/draw_kickers/DrawKickerWorld'; import VertexWorldShaderSource from '../../middle_level/shaders/VertexWorldShader'; import AABB from '../../low_level/math/AABB'; import Vector3 from '../../low_level/math/Vector3'; import Vector2 from '../../low_level/math/Vector2'; import FreeShader from '../../middle_level/shaders/FreeShader'; import Matrix33 from '../math/Matrix33'; export default class Geometry extends GLBoostObject { constructor(glBoostContext) { super(glBoostContext); this._materials = []; this._vertexN = 0; this._vertices = null; this._indicesArray = null; this._indexStartOffsetArray = []; this._performanceHint = null; this._defaultMaterial = null; this._vertexData = []; this._extraDataForShader = {}; this._vboObj = {}; this._AABB = new AABB(); this._drawKicker = DrawKickerWorld.getInstance(); } _createShaderInstance(glBoostContext, shaderClass) { let shaderInstance = new shaderClass(glBoostContext, VertexWorldShaderSource); return shaderInstance; } /** * return all vertex attribute name list */ _allVertexAttribs(vertices) { var attribNameArray = []; for (var attribName in vertices) { if (attribName !== 'components' && attribName !== 'componentBytes' && attribName !== 'componentType') { attribNameArray.push(attribName); } } return attribNameArray; } _checkAndSetVertexComponentNumber(allVertexAttribs) { allVertexAttribs.forEach((attribName)=> { let element = this._vertices[attribName][0]; let componentN = MathClassUtil.compomentNumberOfVector(element); if (componentN === 0) { // if 0, it must be a number. so users must set components info. return; } if (typeof this._vertices.components === 'undefined') { this._vertices.components = {}; } if (typeof this._vertices.componentType === 'undefined') { this._vertices.componentType = {}; } this._vertices.components[attribName] = componentN; this._vertices.componentType[attribName] = 5126; }); } _calcBaryCentricCoord(vertexNum, positionElementNumPerVertex) { this._vertices.barycentricCoord = new Float32Array(vertexNum*positionElementNumPerVertex); this._vertices.components.barycentricCoord = 3; this._vertices.componentType.barycentricCoord = 5126; // gl.FLOAT if (!this._indicesArray) { for (let i=0; i<vertexNum; i++) { this._vertices.barycentricCoord[i*positionElementNumPerVertex+0] = (i % 3 === 0) ? 1 : 0; // 1 0 0 1 0 0 1 0 0 this._vertices.barycentricCoord[i*positionElementNumPerVertex+1] = (i % 3 === 1) ? 1 : 0; // 0 1 0 0 1 0 0 1 0 this._vertices.barycentricCoord[i*positionElementNumPerVertex+2] = (i % 3 === 2) ? 1 : 0; // 0 0 1 0 0 1 0 0 1 } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length; j++) { this._vertices.barycentricCoord[vertexIndices[j]*positionElementNumPerVertex+0] = (j % 3 === 0) ? 1 : 0; // 1 0 0 1 0 0 1 0 0 this._vertices.barycentricCoord[vertexIndices[j]*positionElementNumPerVertex+1] = (j % 3 === 1) ? 1 : 0; // 0 1 0 0 1 0 0 1 0 this._vertices.barycentricCoord[vertexIndices[j]*positionElementNumPerVertex+2] = (j % 3 === 2) ? 1 : 0; // 0 0 1 0 0 1 0 0 1 } } } } _calcTangentPerVertex(pos0Vec3, pos1Vec3, pos2Vec3, uv0Vec2, uv1Vec2, uv2Vec2) { let cp0 = [ new Vector3( pos0Vec3.x, uv0Vec2.x, uv0Vec2.y ), new Vector3( pos0Vec3.y, uv0Vec2.x, uv0Vec2.y ), new Vector3( pos0Vec3.z, uv0Vec2.x, uv0Vec2.y ) ]; let cp1 = [ new Vector3( pos1Vec3.x, uv1Vec2.x, uv1Vec2.y ), new Vector3( pos1Vec3.y, uv1Vec2.x, uv1Vec2.y ), new Vector3( pos1Vec3.z, uv1Vec2.x, uv1Vec2.y ) ]; let cp2 = [ new Vector3( pos2Vec3.x, uv2Vec2.x, uv2Vec2.y ), new Vector3( pos2Vec3.y, uv2Vec2.x, uv2Vec2.y ), new Vector3( pos2Vec3.z, uv2Vec2.x, uv2Vec2.y ) ]; let u = []; let v = []; for ( let i = 0; i < 3; i++ ) { let v1 = Vector3.subtract(cp1[i], cp0[i]); let v2 = Vector3.subtract(cp2[i], cp1[i]); let abc = Vector3.cross(v1, v2); let validate = Math.abs(abc.x) < Number.EPSILON; if (validate) { console.assert(validate, "Polygons or polygons on UV are degenerate!"); return new Vector3(0, 0, 0); } u[i] = - abc.y / abc.x; v[i] = - abc.z / abc.x; } return (new Vector3(u[0], u[1], u[2])).normalize(); } _calcTangentFor3Vertices(vertexIndices, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, uv0IndexBase, uv1IndexBase, uv2IndexBase, incrementNum) { let pos0Vec3 = new Vector3( this._vertices.position[pos0IndexBase], this._vertices.position[pos0IndexBase + 1], this._vertices.position[pos0IndexBase + 2] ); let pos1Vec3 = new Vector3( this._vertices.position[pos1IndexBase], this._vertices.position[pos1IndexBase + 1], this._vertices.position[pos1IndexBase + 2] ); let pos2Vec3 = new Vector3( this._vertices.position[pos2IndexBase], this._vertices.position[pos2IndexBase + 1], this._vertices.position[pos2IndexBase + 2] ); let uv0Vec2 = new Vector2( this._vertices.texcoord[uv0IndexBase], this._vertices.texcoord[uv0IndexBase + 1] ); let uv1Vec2 = new Vector2( this._vertices.texcoord[uv1IndexBase], this._vertices.texcoord[uv1IndexBase + 1] ); let uv2Vec2 = new Vector2( this._vertices.texcoord[uv2IndexBase], this._vertices.texcoord[uv2IndexBase + 1] ); const componentNum3 = 3; let tan0IndexBase = (i ) * componentNum3; let tan1IndexBase = (i + 1) * componentNum3; let tan2IndexBase = (i + 2) * componentNum3; if (vertexIndices) { tan0IndexBase = vertexIndices[i] * componentNum3; tan1IndexBase = vertexIndices[i + 1] * componentNum3; tan2IndexBase = vertexIndices[i + 2] * componentNum3; } let tan0Vec3 = this._calcTangentPerVertex(pos0Vec3, pos1Vec3, pos2Vec3, uv0Vec2, uv1Vec2, uv2Vec2); this._vertices.tangent[tan0IndexBase] = tan0Vec3.x; this._vertices.tangent[tan0IndexBase + 1] = tan0Vec3.y; this._vertices.tangent[tan0IndexBase + 2] = tan0Vec3.z; let tan1Vec3 = this._calcTangentPerVertex(pos1Vec3, pos2Vec3, pos0Vec3, uv1Vec2, uv2Vec2, uv0Vec2); this._vertices.tangent[tan1IndexBase] = tan1Vec3.x; this._vertices.tangent[tan1IndexBase + 1] = tan1Vec3.y; this._vertices.tangent[tan1IndexBase + 2] = tan1Vec3.z; let tan2Vec3 = this._calcTangentPerVertex(pos2Vec3, pos0Vec3, pos1Vec3, uv2Vec2, uv0Vec2, uv1Vec2); this._vertices.tangent[tan2IndexBase] = tan2Vec3.x; this._vertices.tangent[tan2IndexBase + 1] = tan2Vec3.y; this._vertices.tangent[tan2IndexBase + 2] = tan2Vec3.z; } _calcTangent(vertexNum, positionElementNumPerVertex, texcoordElementNumPerVertex, primitiveType) { this._vertices.tangent = new Float32Array(vertexNum*positionElementNumPerVertex); this._vertices.components.tangent = 3; this._vertices.componentType.tangent = 5126; // gl.FLOAT let incrementNum = 3; // gl.TRIANGLES if (primitiveType === GLBoost.TRIANGLE_STRIP) { // gl.TRIANGLE_STRIP incrementNum = 1; } if ( this._vertices.texcoord ) { if (!this._indicesArray) { for (let i=0; i<vertexNum-2; i+=incrementNum) { let pos0IndexBase = i * positionElementNumPerVertex; let pos1IndexBase = (i + 1) * positionElementNumPerVertex; let pos2IndexBase = (i + 2) * positionElementNumPerVertex; let uv0IndexBase = i * texcoordElementNumPerVertex; let uv1IndexBase = (i + 1) * texcoordElementNumPerVertex; let uv2IndexBase = (i + 2) * texcoordElementNumPerVertex; this._calcTangentFor3Vertices(null, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, uv0IndexBase, uv1IndexBase, uv2IndexBase, incrementNum); } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length-2; j+=incrementNum) { let pos0IndexBase = vertexIndices[j ] * positionElementNumPerVertex; /// 0つ目の頂点 let pos1IndexBase = vertexIndices[j + 1] * positionElementNumPerVertex; /// 1つ目の頂点 let pos2IndexBase = vertexIndices[j + 2] * positionElementNumPerVertex; /// 2つ目の頂点 let uv0IndexBase = vertexIndices[j ] * texcoordElementNumPerVertex; let uv1IndexBase = vertexIndices[j + 1] * texcoordElementNumPerVertex; let uv2IndexBase = vertexIndices[j + 2] * texcoordElementNumPerVertex; this._calcTangentFor3Vertices(vertexIndices, j, pos0IndexBase, pos1IndexBase, pos2IndexBase, uv0IndexBase, uv1IndexBase, uv2IndexBase, incrementNum); } } } } } setVerticesData(vertices, indicesArray, primitiveType = GLBoost.TRIANGLES, performanceHint = GLBoost.STATIC_DRAW) { this._vertices = vertices; this._indicesArray = indicesArray; let allVertexAttribs = this._allVertexAttribs(this._vertices); this._checkAndSetVertexComponentNumber(allVertexAttribs); let vertexNum = 0; let positionElementNum = 0; let positionElementNumPerVertex = this._vertices.components.position; let texcoordElementNumPerVertex = this._vertices.components.texcoord; if (typeof this._vertices.position.buffer !== 'undefined') { vertexNum = this._vertices.position.length / positionElementNumPerVertex; positionElementNum = this._vertices.position.length; } else { vertexNum = this._vertices.position.length; // vertices must be type of Vector3 positionElementNum = this._vertices.position.length * positionElementNumPerVertex; } // for Wireframe this._calcBaryCentricCoord(vertexNum, positionElementNumPerVertex); allVertexAttribs = this._allVertexAttribs(this._vertices); this._checkAndSetVertexComponentNumber(allVertexAttribs); // vector to array allVertexAttribs.forEach((attribName)=> { if (attribName === 'barycentricCoord') { return; } if (attribName === 'tangent') { return; } if (typeof this._vertices[attribName].buffer !== 'undefined') { return; } let vertexAttribArray = []; this._vertices[attribName].forEach((elem, index) => { let element = this._vertices[attribName][index]; Array.prototype.push.apply(vertexAttribArray, MathClassUtil.vectorToArray(element)); }); this._vertices[attribName] = vertexAttribArray; }); // for Tangent if (this._vertices.texcoord) { this._calcTangent(vertexNum, positionElementNumPerVertex, texcoordElementNumPerVertex, primitiveType); } // for Raycast Picking this._calcArenbergInverseMatrices(primitiveType); // Normal Array to Float32Array allVertexAttribs.forEach((attribName)=> { if (typeof this._vertices[attribName].buffer === 'undefined') { this._vertices[attribName] = new Float32Array(this._vertices[attribName]); } }); for (let i=0; i<vertexNum; i++) { this._AABB.addPositionWithArray(this._vertices.position, i * positionElementNumPerVertex); } this._AABB.updateAllInfo(); let gl = this._glContext.gl; let primitiveTypeStr = GLBoost.getValueOfGLBoostConstant(primitiveType); this._primitiveType = gl[primitiveTypeStr]; let performanceHintStr = GLBoost.getValueOfGLBoostConstant(performanceHint); this._performanceHint = gl[performanceHintStr]; } updateVerticesData(vertices, skipUpdateAABB = false) { let gl = this._glContext.gl; for (let attribName in vertices) { let vertexAttribArray = []; this._vertices[attribName].forEach((elem, index) => { let element = vertices[attribName][index]; Array.prototype.push.apply(vertexAttribArray, MathClassUtil.vectorToArray(element)); if (attribName === 'position' && !(skipUpdateAABB === true)) { let componentN = this._vertices.components[attribName]; this._AABB.addPositionWithArray(vertexAttribArray, index * componentN); } this._vertices[attribName] = vertexAttribArray; }); } if(!(skipUpdateAABB === true)) { this._AABB.updateAllInfo(); } for (let attribName in vertices) { if (this._vboObj[attribName]) { let float32AryVertexData = new Float32Array(this._vertices[attribName]); gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.bufferSubData(gl.ARRAY_BUFFER, 0, float32AryVertexData); gl.bindBuffer(gl.ARRAY_BUFFER, null); } else { return false; } } return true; } setUpVertexAttribs(gl, glslProgram, allVertexAttribs) { var optimizedVertexAttribs = glslProgram.optimizedVertexAttribs; // setup vertex layouts allVertexAttribs.forEach((attribName)=> { if (optimizedVertexAttribs.indexOf(attribName) != -1) { let vertexAttribName = null; gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.vertexAttribPointer(glslProgram['vertexAttribute_' + attribName], this._vertices.components[attribName], this._vertices.componentType[attribName], false, 0, 0); } }); } setUpEnableVertexAttribArrays(gl, glslProgram, allVertexAttribs) { var optimizedVertexAttribs = glslProgram.optimizedVertexAttribs; allVertexAttribs.forEach((attribName)=> { if (optimizedVertexAttribs.indexOf(attribName) != -1) { gl.enableVertexAttribArray(glslProgram['vertexAttribute_' + attribName]); } }); } setUpDisableAllVertexAttribArrays(gl, glslProgram) { for (let i=0; i<8; i++) { gl.disableVertexAttribArray(i); } } setUpDisableVertexAttribArrays(gl, glslProgram, allVertexAttribs) { var optimizedVertexAttribs = glslProgram.optimizedVertexAttribs; allVertexAttribs.forEach((attribName)=> { if (optimizedVertexAttribs.indexOf(attribName) != -1) { gl.disableVertexAttribArray(glslProgram['vertexAttribute_' + attribName]); } }); } _getVAO() { return Geometry._vaoDic[this.toString()]; } _getAllVertexAttribs() { return this._allVertexAttribs(this._vertices); } prepareGLSLProgram(expression, material, existCamera_f, lights, shaderClass = void 0, argShaderInstance = void 0) { let vertices = this._vertices; let _optimizedVertexAttribs = this._allVertexAttribs(vertices, material); let shaderInstance = null; if (argShaderInstance) { shaderInstance = argShaderInstance; } else { if (shaderClass) { shaderInstance = this._createShaderInstance(this._glBoostSystem, shaderClass); } else { shaderInstance = this._createShaderInstance(this._glBoostSystem, material.shaderClass); } } shaderInstance.getShaderProgram(expression, _optimizedVertexAttribs, existCamera_f, lights, material, this._extraDataForShader); return shaderInstance; } _setVertexNtoSingleMaterial(material, index) { // if this mesh has only one material... //if (material.getVertexN(this) === 0) { if (this._indicesArray && this._indicesArray.length > 0) { material.setVertexN(this, this._indicesArray[index].length); } else { material.setVertexN(this, this._vertexN); } //} } _getAppropriateMaterials(mesh) { let materials = null; if (this._materials.length > 0) { materials = this._materials; } else if (mesh.material){ materials = [mesh.material]; } else { mesh.material = this._glBoostSystem._defaultMaterial; materials = [mesh.material]; } return materials; } getIndexStartOffsetArrayAtMaterial(i) { return this._indexStartOffsetArray[i]; } prepareToRender(expression, existCamera_f, lights, meshMaterial, mesh, shaderClass = void 0, argMaterials = void 0) { var vertices = this._vertices; var gl = this._glContext.gl; var glem = GLExtensionsManager.getInstance(this._glContext); this._vertexN = vertices.position.length / vertices.components.position; var allVertexAttribs = this._allVertexAttribs(vertices); // create VAO if (Geometry._vaoDic[this.toString()]) { } else { var vao = this._glContext.createVertexArray(this); Geometry._vaoDic[this.toString()] = vao; } glem.bindVertexArray(gl, Geometry._vaoDic[this.toString()]); let doAfter = false; allVertexAttribs.forEach((attribName)=> { // create VBO if (this._vboObj[attribName]) { gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); } else { let vbo = this._glContext.createBuffer(this); this._vboObj[attribName] = vbo; gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); // if (typeof this._vertices[attribName].buffer !== 'undefined') { gl.bufferData(gl.ARRAY_BUFFER, this._vertices[attribName], this._performanceHint); // } else { // gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this._vertices[attribName]), this._performanceHint); // } //gl.bindBuffer(gl.ARRAY_BUFFER, null); doAfter = true; } }); if (doAfter) { if (Geometry._iboArrayDic[this.toString()]) { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Geometry._iboArrayDic[this.toString()] ); } else { if (this._indicesArray) { let indices = []; for (let i=0; i<this._indicesArray.length; i++) { if (i==0) { this._indexStartOffsetArray[i] = 0; } this._indexStartOffsetArray[i+1] = this._indexStartOffsetArray[i] + this._indicesArray[i].length; //Array.prototype.push.apply(indices, this._indicesArray[i]); indices = indices.concat(this._indicesArray[i]); } // create Index Buffer var ibo = this._glContext.createBuffer(this); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo ); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, glem.createUintArrayForElementIndex(gl, indices), gl.STATIC_DRAW); Geometry._iboArrayDic[this.toString()] = ibo; } } } let materials = argMaterials; if (argMaterials === void 0) { materials = this._getAppropriateMaterials(mesh); } //let materials = this._getAppropriateMaterials(mesh); for (let i=0; i<materials.length;i++) { let shaderInstance = null; /* if (argMaterials !== void 0 && argMaterials[i].shaderInstance !== null) { shaderInstance = argMaterials[i].shaderInstance; } else if (materials[i].shaderInstance !== null) { shaderInstance = materials[i].shaderInstance; } else { */ if (materials[i].shaderInstance && materials[i].shaderInstance.constructor === FreeShader) { shaderInstance = this.prepareGLSLProgram(expression, materials[i], existCamera_f, lights, void 0, materials[i].shaderInstance); } else { shaderInstance = this.prepareGLSLProgram(expression, materials[i], existCamera_f, lights, shaderClass); } // } this._setVertexNtoSingleMaterial(materials[i], i); shaderInstance.vao = Geometry._vaoDic[this.toString()]; this.setUpVertexAttribs(gl, shaderInstance._glslProgram, allVertexAttribs); if (argMaterials === void 0) { materials[i].shaderInstance = shaderInstance; } else { argMaterials[i].shaderInstance = shaderInstance; } } glem.bindVertexArray(gl, null); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); return materials; } _setUpVertexAttibsWrapper(glslProgram) { this.setUpVertexAttribs(this._glContext.gl, glslProgram, this._getAllVertexAttribs()); } draw(data) { const gl = this._glContext.gl; const glem = GLExtensionsManager.getInstance(this._glContext); let materials = this._getAppropriateMaterials(data.mesh); const thisName = this.toString(); this._drawKicker.draw( { gl: gl, glem: glem, expression: data.expression, lights: data.lights, camera: data.camera, mesh: data.mesh, scene: data.scene, renderPassIndex: data.renderPassIndex, materials: materials, vertices: this._vertices, vaoDic: Geometry._vaoDic, vboObj: this._vboObj, iboArrayDic: Geometry._iboArrayDic, geometry: this, geometryName: thisName, primitiveType: this._primitiveType, vertexN: this._vertexN, viewport: data.viewport, isWebVRMode: data.isWebVRMode, webvrFrameData: data.webvrFrameData, forceThisMaterial: data.forceThisMaterial }); } drawIntermediate() {} merge(geometrys) { if (Array.isArray(geometrys)) { let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let allGeomLength = 0; geometrys.forEach((geometry) => { allGeomLength += geometry._vertices[attribName].length; }); typedArrayDic[attribName] = new Float32Array(thisLength + allGeomLength); }); let lastThisLengthDic = {}; allVertexAttribs.forEach((attribName)=> { lastThisLengthDic[attribName] = 0; }); geometrys.forEach((geometry, index) => { let typedSubArrayDic = {}; allVertexAttribs.forEach((attribName)=> { let typedArray = typedArrayDic[attribName]; if (index === 0) { lastThisLengthDic[attribName] = geometrys[index]._vertices[attribName].length; } let end = (typeof geometrys[index+1] !== 'undefined') ? lastThisLengthDic[attribName] + geometrys[index+1]._vertices[attribName].length : void 0; typedSubArrayDic[attribName] = typedArray.subarray(0, end); lastThisLengthDic[attribName] = end; }); this.mergeInner(geometry, typedSubArrayDic, (index === 0)); }); } else { let geometry = geometrys; let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; typedArrayDic[attribName] = new Float32Array(thisLength + geomLength); }); this.mergeInner(geometry, typedArrayDic); } } /** * */ mergeInner(geometry, typedArrayDic, isFirst = false) { let gl = this._glContext.gl; let baseLen = this._vertices.position.length / this._vertices.components.position;; if (this === geometry) { console.assert('don\'t merge same geometry!'); } let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; let float32array = typedArrayDic[attribName]; if (isFirst) { float32array.set(this._vertices[attribName], 0); } float32array.set(geometry._vertices[attribName], thisLength); this._vertices[attribName] = float32array; if (typeof this._vboObj[attribName] !== 'undefined') { gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.bufferData(gl.ARRAY_BUFFER, this._vertices[attribName], this._performanceHint); gl.bindBuffer(gl.ARRAY_BUFFER, null); } }); let geometryIndicesN = geometry._indicesArray.length; for (let i = 0; i < geometryIndicesN; i++) { for (let j = 0; j < geometry._indicesArray[i].length; j++) { geometry._indicesArray[i][j] += baseLen; } this._indicesArray.push(geometry._indicesArray[i]); if (geometry._materials[i]) { this._materials.push(geometry._materials[i]); } } this._vertexN += geometry._vertexN; } mergeHarder(geometrys) { if (Array.isArray(geometrys)) { let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let allGeomLength = 0; geometrys.forEach((geometry) => { allGeomLength += geometry._vertices[attribName].length; }); typedArrayDic[attribName] = new Float32Array(thisLength + allGeomLength); }); let lastThisLengthDic = {}; allVertexAttribs.forEach((attribName)=> { lastThisLengthDic[attribName] = 0; }); geometrys.forEach((geometry, index) => { let typedSubArrayDic = {}; allVertexAttribs.forEach((attribName)=> { let typedArray = typedArrayDic[attribName]; if (index === 0) { lastThisLengthDic[attribName] = geometrys[index]._vertices[attribName].length; } let end = (typeof geometrys[index+1] !== 'undefined') ? lastThisLengthDic[attribName] + geometrys[index+1]._vertices[attribName].length : void 0; typedSubArrayDic[attribName] = typedArray.subarray(0, end); lastThisLengthDic[attribName] = end; }); this.mergeHarderInner(geometry, typedSubArrayDic, (index === 0)); }); } else { let geometry = geometrys; let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; typedArrayDic[attribName] = new Float32Array(thisLength + geomLength); }); this.mergeHarderInner(geometry, typedArrayDic); } } /** * take no thought geometry's materials * */ mergeHarderInner(geometry, typedArrayDic, isFirst = false) { let gl = this._glContext.gl; let baseLen = this._vertices.position.length / this._vertices.components.position; if (this === geometry) { console.assert('don\'t merge same geometry!'); } let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; let float32array = typedArrayDic[attribName]; if (isFirst) { float32array.set(this._vertices[attribName], 0); } float32array.set(geometry._vertices[attribName], thisLength); this._vertices[attribName] = float32array; if (typeof this._vboObj[attribName] !== 'undefined') { gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.bufferData(gl.ARRAY_BUFFER, this._vertices[attribName], this._performanceHint); gl.bindBuffer(gl.ARRAY_BUFFER, null); } }); for (let i = 0; i < this._indicesArray.length; i++) { let len = geometry._indicesArray[i].length; for (let j = 0; j < len; j++) { let idx = geometry._indicesArray[i][j]; this._indicesArray[i].push(baseLen + idx); } if (this._materials[i]) { this._materials[i].setVertexN(this, this._materials[i].getVertexN(geometry)); } } this._vertexN += geometry._vertexN; } set materials(materials) { this._materials = materials; } get materials() { return this._materials; } get centerPosition() { return this._AABB.centerPoint; } setExtraDataForShader(name, value) { this._extraDataForShader[name] = value; } getExtraDataForShader(name) { return this._extraDataForShader[name]; } isTransparent(mesh) { let materials = this._getAppropriateMaterials(mesh); let isTransparent = false; materials.forEach((material)=>{ if (material.isTransparent()) { isTransparent = true; } }); return isTransparent; } get AABB() { return this._AABB;//.clone(); } get rawAABB() { return this._AABB; } isIndexed() { return !!Geometry._iboArrayDic[this.toString()]; } getTriangleCount(mesh) { let gl = this._glContext.gl; let materials = this._getAppropriateMaterials(mesh); let count = 0; for (let i=0; i<materials.length;i++) { let material = materials[i]; if (this._primitiveType === gl.TRIANGLES) { if (this.isIndexed()) { count += material.getVertexN(this.toString()) / 3; } else { count += this._vertexN / 3; } } else if (this._primitiveType === gl.TRIANGLE_STRIP) { if (this.isIndexed()) { count += material.getVertexN(this.toString()) - 2; } else { count += this._vertexN - 2; } } } return count; } getVertexCount() { let gl = this._glContext.gl; let count = 0; if (this._vertices) { count = this._vertices.position.length; } return count; } rayCast(origVec3, dirVec3, isFrontFacePickable, isBackFacePickable) { let currentShortestT = Number.MAX_VALUE; let currentShortestIntersectedPosVec3 = null; const positionElementNumPerVertex = this._vertices.components.position; let incrementNum = 3; // gl.TRIANGLES if (this._primitiveType === GLBoost.TRIANGLE_STRIP) { // gl.TRIANGLE_STRIP incrementNum = 1; } if (!this._indicesArray) { for (let i=0; i<vertexNum; i++) { const j = i * incrementNum; let pos0IndexBase = j * positionElementNumPerVertex; let pos1IndexBase = (j + 1) * positionElementNumPerVertex; let pos2IndexBase = (j + 2) * positionElementNumPerVertex; const result = this._rayCastInner(origVec3, dirVec3, j, pos0IndexBase, pos1IndexBase, pos2IndexBase, isFrontFacePickable, isBackFacePickable); if (result === null) { continue; } const t = result[0]; if (result[0] < currentShortestT) { currentShortestT = t; currentShortestIntersectedPosVec3 = result[1]; } } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length; j++) { const k = j * incrementNum; let pos0IndexBase = vertexIndices[k ] * positionElementNumPerVertex; let pos1IndexBase = vertexIndices[k + 1] * positionElementNumPerVertex; let pos2IndexBase = vertexIndices[k + 2] * positionElementNumPerVertex; if (vertexIndices[k + 2] === void 0) { break; } const result = this._rayCastInner(origVec3, dirVec3, vertexIndices[k], pos0IndexBase, pos1IndexBase, pos2IndexBase, isFrontFacePickable, isBackFacePickable); if (result === null) { continue; } const t = result[0]; if (result[0] < currentShortestT) { currentShortestT = t; currentShortestIntersectedPosVec3 = result[1]; } } } } return [currentShortestIntersectedPosVec3, currentShortestT]; } _rayCastInner(origVec3, dirVec3, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, isFrontFacePickable, isBackFacePickable) { if (!this._vertices.arenberg3rdPosition[i]) { return null; } const faceNormal = this._vertices.faceNormal[i]; if (faceNormal.dotProduct(dirVec3) < 0 && !isFrontFacePickable) { // ---> <--- return null; } if (faceNormal.dotProduct(dirVec3) > 0 && !isBackFacePickable) { // ---> ---> return null; } const vec3 = Vector3.subtract(origVec3, this._vertices.arenberg3rdPosition[i]); const convertedOrigVec3 = this._vertices.inverseArenbergMatrix[i].multiplyVector(vec3); const convertedDirVec3 = this._vertices.inverseArenbergMatrix[i].multiplyVector(dirVec3); if (convertedDirVec3.z >= -(1e-6) && convertedDirVec3.z <= (1e-6)) { return null; } const t = -convertedOrigVec3.z / convertedDirVec3.z; if(t <= (1e-5)) { return null; } const u = convertedOrigVec3.x + t * convertedDirVec3.x; const v = convertedOrigVec3.y + t * convertedDirVec3.y; if (u < 0.0 || v < 0.0 || (u + v) > 1.0) { return null; } const fDat = 1.0 - u - v; const pos0Vec3 = new Vector3( this._vertices.position[pos0IndexBase], this._vertices.position[pos0IndexBase + 1], this._vertices.position[pos0IndexBase + 2] ); const pos1Vec3 = new Vector3( this._vertices.position[pos1IndexBase], this._vertices.position[pos1IndexBase + 1], this._vertices.position[pos1IndexBase + 2] ); const pos2Vec3 = new Vector3( this._vertices.position[pos2IndexBase], this._vertices.position[pos2IndexBase + 1], this._vertices.position[pos2IndexBase + 2] ); const pos0 = Vector3.multiply(pos0Vec3, u); const pos1 = Vector3.multiply(pos1Vec3, v); const pos2 = Vector3.multiply(pos2Vec3, fDat); const intersectedPosVec3 = Vector3.add(Vector3.add(pos0, pos1), pos2); return [t, intersectedPosVec3]; } _calcArenbergInverseMatrices(primitiveType) { const positionElementNumPerVertex = this._vertices.components.position; let incrementNum = 3; // gl.TRIANGLES if (primitiveType === GLBoost.TRIANGLE_STRIP) { // gl.TRIANGLE_STRIP incrementNum = 1; } this._vertices.inverseArenbergMatrix = []; this._vertices.arenberg3rdPosition = []; this._vertices.faceNormal = []; if (!this._indicesArray) { for (let i=0; i<this._vertexN-2; i+=incrementNum) { let pos0IndexBase = i * positionElementNumPerVertex; let pos1IndexBase = (i + 1) * positionElementNumPerVertex; let pos2IndexBase = (i + 2) * positionElementNumPerVertex; this._calcArenbergMatrixFor3Vertices(null, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, incrementNum); } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length-2; j+=incrementNum) { let pos0IndexBase = vertexIndices[j ] * positionElementNumPerVertex; let pos1IndexBase = vertexIndices[j + 1] * positionElementNumPerVertex; let pos2IndexBase = vertexIndices[j + 2] * positionElementNumPerVertex; if (vertexIndices[j + 2] === void 0) { break; } this._calcArenbergMatrixFor3Vertices(vertexIndices, j, pos0IndexBase, pos1IndexBase, pos2IndexBase, incrementNum); } } } } _calcArenbergMatrixFor3Vertices(vertexIndices, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, incrementNum) { const pos0Vec3 = new Vector3( this._vertices.position[pos0IndexBase], this._vertices.position[pos0IndexBase + 1], this._vertices.position[pos0IndexBase + 2] ); const pos1Vec3 = new Vector3( this._vertices.position[pos1IndexBase], this._vertices.position[pos1IndexBase + 1], this._vertices.position[pos1IndexBase + 2] ); const pos2Vec3 = new Vector3( this._vertices.position[pos2IndexBase], this._vertices.position[pos2IndexBase + 1], this._vertices.position[pos2IndexBase + 2] ); const ax = pos0Vec3.x - pos2Vec3.x; const ay = pos0Vec3.y - pos2Vec3.y; const az = pos0Vec3.z - pos2Vec3.z; const bx = pos1Vec3.x - pos2Vec3.x; const by = pos1Vec3.y - pos2Vec3.y; const bz = pos1Vec3.z - pos2Vec3.z; let nx = ay * bz - az * by; let ny = az * bx - ax * bz; let nz = ax * by - ay * bx; let da = Math.sqrt(nx * nx + ny * ny + nz * nz); if (da <= 1e-6) { return 0; } da = 1.0 / da; nx *= da; ny *= da; nz *= da; const arenbergMatrix = new Matrix33( pos0Vec3.x - pos2Vec3.x, pos1Vec3.x - pos2Vec3.x, nx - pos2Vec3.x, pos0Vec3.y - pos2Vec3.y, pos1Vec3.y - pos2Vec3.y, ny - pos2Vec3.y, pos0Vec3.z - pos2Vec3.z, pos1Vec3.z - pos2Vec3.z, nz - pos2Vec3.z ); const inverseArenbergMatrix = arenbergMatrix.invert(); let arenberg0IndexBase = (i ); let arenberg1IndexBase = (i + 1); let arenberg2IndexBase = (i + 2); if (vertexIndices) { arenberg0IndexBase = vertexIndices[i]; arenberg1IndexBase = vertexIndices[i + 1]; arenberg2IndexBase = vertexIndices[i + 2]; } // const triangleIdx = i/incrementNum; this._vertices.inverseArenbergMatrix[arenberg0IndexBase] = inverseArenbergMatrix; this._vertices.arenberg3rdPosition[arenberg0IndexBase] = pos2Vec3; this._vertices.faceNormal[arenberg0IndexBase] = new Vector3(nx, ny, nz); } } Geometry._vaoDic = {}; Geometry._iboArrayDic = {};
cx20/GLBoost
src/low_level/geometries/Geometry.js
JavaScript
mit
37,614
/*!-------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ /*--------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ define("vs/workbench/parts/git/node/askpass.nls", { "vs/base/common/errors": [ "{0}. Error code: {1}", "Permission Denied (HTTP {0})", "Permission Denied", "{0} (HTTP {1}: {2})", "{0} (HTTP {1})", "Unknown Connection Error ({0})", "An unknown connection error occurred. Either you are no longer connected to the internet or the server you are connected to is offline.", "{0}: {1}", "An unknown error occurred. Please consult the log for more details.", "A system error occured ({0})", "An unknown error occurred. Please consult the log for more details.", "{0} ({1} errors in total)", "An unknown error occurred. Please consult the log for more details.", "Not Implemented", "Illegal argument: {0}", "Illegal argument", "Illegal state: {0}", "Illegal state", "Failed to load a required file. Either you are no longer connected to the internet or the server you are connected to is offline. Please refresh the browser to try again.", "Failed to load a required file. Please restart the application to try again. Details: {0}" ] });
KTXSoftware/KodeStudio-linux32
resources/app/out/vs/workbench/parts/git/node/askpass.nls.js
JavaScript
mit
1,436
import { CodeNameCodeSequenceValues } from '../enums'; import getSequenceAsArray from './getSequenceAsArray'; import getMergedContentSequencesByTrackingUniqueIdentifiers from './getMergedContentSequencesByTrackingUniqueIdentifiers'; import processMeasurement from './processMeasurement'; const getMeasurements = ( ImagingMeasurementReportContentSequence, displaySet ) => { const ImagingMeasurements = ImagingMeasurementReportContentSequence.find( item => item.ConceptNameCodeSequence.CodeValue === CodeNameCodeSequenceValues.ImagingMeasurements ); const MeasurementGroups = getSequenceAsArray( ImagingMeasurements.ContentSequence ).filter( item => item.ConceptNameCodeSequence.CodeValue === CodeNameCodeSequenceValues.MeasurementGroup ); const mergedContentSequencesByTrackingUniqueIdentifiers = getMergedContentSequencesByTrackingUniqueIdentifiers( MeasurementGroups ); let measurements = []; Object.keys(mergedContentSequencesByTrackingUniqueIdentifiers).forEach( trackingUniqueIdentifier => { const mergedContentSequence = mergedContentSequencesByTrackingUniqueIdentifiers[ trackingUniqueIdentifier ]; const measurement = processMeasurement(mergedContentSequence, displaySet); if (measurement) { measurements.push(measurement); } } ); return measurements; }; export default getMeasurements;
OHIF/Viewers
platform/core/src/DICOMSR/SCOORD3D/utils/getMeasurements.js
JavaScript
mit
1,434
describe('GET /docs/:docUUID', function() { beforeEach(function *() { yield fixtures.load(); this.reader = fixtures.users[1]; yield this.reader.addTeam(fixtures.teams[0]); yield fixtures.teams[0].addProject(fixtures.projects[0], { permission: 'read' }); this.collection = fixtures.collections[0]; yield fixtures.projects[0].addCollection(this.collection); this.doc = fixtures.docs[0]; yield this.collection.addDoc(this.doc); }); it('should return Unauthorized when user is unauthorized', function *() { try { yield API.docs(this.doc.UUID).get(); throw new Error('should reject'); } catch (err) { expect(err).to.be.an.error(HTTP_ERROR.Unauthorized); } }); it('should return NotFound when doc is not found', function *() { try { yield API.$auth(this.reader.email, this.reader.password).docs('not exists UUID').get(); throw new Error('should reject'); } catch (err) { expect(err).to.be.an.error(HTTP_ERROR.NotFound); } }); it('should return NoPermission when the user don\'t have read permission', function *() { var guest = fixtures.users[2]; try { yield API.$auth(guest.email, guest.password).docs(this.doc.UUID).get(); throw new Error('should reject'); } catch (err) { expect(err).to.be.an.error(HTTP_ERROR.NoPermission); } }); it('should return the current version', function *() { yield Doc.createWithTransaction({ UUID: this.doc.UUID, CollectionId: this.doc.CollectionId, title: 'new title', content: 'new content' }); var doc = yield API.$auth(this.reader.email, this.reader.password).docs(this.doc.UUID).get(); expect(doc.title).to.eql('new title'); expect(doc.content).to.eql('new content'); expect(doc.current).to.eql(true); expect(doc.UUID).to.eql(this.doc.UUID); }); describe('?version=:version', function() { it('should return the specified version', function *() { var version1 = yield Doc.createWithTransaction({ UUID: this.doc.UUID, CollectionId: this.doc.CollectionId, title: 'version1', content: 'version 1' }); var version2 = yield Doc.createWithTransaction({ UUID: this.doc.UUID, CollectionId: this.doc.CollectionId, title: 'version2', content: 'version 2' }); var doc = yield API.$auth(this.reader.email, this.reader.password).docs(this.doc.UUID).get({ version: version1.version }); expect(doc.title).to.eql(version1.title); expect(doc.content).to.eql(version1.content); expect(doc.version).to.eql(version1.version); }); }); });
wikilab/wikilab-api
test/api/routes/docs/get_doc.js
JavaScript
mit
2,676
var test = require('tape') var secstamp = require('../') test('generates seconds properly', function (t) { t.equals(secstamp(42), '0:42') t.end() }) test('accepts string as input', function (t) { t.equals(secstamp(42), secstamp('42')) t.end() }) test('pads periods with 0s if needed', function (t) { t.equals(secstamp(34), '0:34', "doesn't pad seconds greater than 10") t.equals(secstamp(0), '0:00', 'pads seconds less than 10') t.equals(secstamp(1), '0:01', 'pads seconds less than 10') t.equals(secstamp(63), '1:03', "doesn't pad minutes when no hours present") t.equals(secstamp(4357), '1:12:37', "doesn't pad minutes when hours present and minutes >= 10") t.equals(secstamp(3657), '1:00:57', "pads minutes when hours present and minutes < 10") t.equals(secstamp(31337), '8:42:17', "doesn't pad minutes when minutes > 10") t.end() }) test("returns null if input isn't a number", function (t) { t.equals(secstamp('potato'), null) t.equals(secstamp(''), null) t.equals(secstamp(null), null) t.equals(secstamp(), null) t.end() })
sidd/secstamp
test/index.js
JavaScript
mit
1,068
import { routerStateReducer as router } from 'redux-router'; import { combineReducers } from 'redux'; import entities from './entities'; import app from './app'; import cardList from './cardList'; const rootReducer = combineReducers({ router, entities, app, cardList }); export default rootReducer;
Poplava/mtg-cards
client/reducers/index.js
JavaScript
mit
310
import React from 'react'; import PropTypes from 'prop-types'; import Navbar from './Navbar'; import Footer from './Footer'; class Layout extends React.Component { render() { return ( <div className='grid'> <Navbar /> <div className="container"> {this.props.children} </div> </div> ); } } Layout.propTypes = { children: PropTypes.element }; export default Layout;
dziksu/songs-manager
src/layouts/Layout.js
JavaScript
mit
429
/* * tiny-node.js * Description : A modern JavaScript utility library for browser. * Coder : shusiwei * Date : 2016-08-22 * Version : 1.0.0 * * https://github.com/shusiwei/tiny-node * Licensed under the MIT license. */ import {isUndefined, isNull, isPlainObject, isString, forEach, isPosiInteger, trim} from './index'; const {document} = window; const addEventListener = (el, fn, ...types) => { if (types.length === 0) throw new Error('at least one event name is required'); for (let type of types) { el.addEventListener(type, fn); }; return el; }; const removeEventListener = (el, fn, ...types) => { if (types.length === 0) throw new Error('at least one event name is required'); for (let type of types) { el.removeEventListener(type, fn); }; return el; }; /** * @name 创建一个带有类似数组长度的Object对象 * * @return 返回该对象 */ const makeArrayLikeObject = () => Object.defineProperty({}, 'length', {value: 0, writable: true, enumerable: false}); /** * @name 将一个对象序列化为一个queryString字符串 * * @param {Object} source * 操作的对象 * * @return {String} queryString字符串 */ export const serialize = (...sources) => { if (sources.length === 0) return ''; const result = []; for (let source of sources) { if (!isPlainObject(source)) throw new TypeError('source must b a plain Object'); for (let key in source) { if (!isUndefined(source[key]) && !isNull(source[key])) result.push(key + '=' + encodeURIComponent(trim(source[key].toString()))); }; }; return result.join('&'); }; /** * @name 将一个queryString字符串转化成一个对象 * * @param {String} source * 操作的对象 * @param {String} keys 需要返回值的key * * @return {Object} 当keys参数为空时,返回该对象,当keys参数只有一个时,则返回该对象中key为此参数的值,当keys参数有多个时,则以一个对象的形式返回该对象所有keys中的参数的值 */ export const queryParse = (source, ...keys) => { if (!isString(source)) throw new TypeError('source must b a String'); const result = makeArrayLikeObject(); forEach(source.replace(/^\?/, '').split('&'), string => { const item = string.split('='); result[item[0]] = item[1]; result.length++; }); if (keys.length === 0) return result; if (keys.length === 1) return result[keys[0]]; const dumpData = makeArrayLikeObject(); forEach(keys, key => { dumpData[key] = result[key]; dumpData.length++; }); return dumpData; }; /** * @name 将cookie字符串转化成一个对象 * * @param {String} keys 需要返回值的key * * @return {Object} 当keys参数为空时,返回该对象,当keys参数只有一个时,则返回该对象中key为此参数的值,当keys参数有多个时,则以一个对象的形式返回该对象所有keys中的参数的值 */ export const cookieParse = (...keys) => queryParse(document.cookie.replace(/; /g, '&'), ...keys); /** * @name 设置cookie * * @param {String} name * cookie名称 * @param {String} value * cookie值 * @param {Object} options 过期天数&其它参数 * @param {String} options.path cookie所在路径 * @param {String} options.domain cookie所在域 * @param {String} options.secure cookie是否只允许在安全链接中读取 */ export const setCookie = (name, value, ...options) => { let cookie = name + '=' + value; for (let option of options) { if (isPosiInteger(option)) { const date = new Date(); date.setTime(date.getTime() + option * 24 * 60 * 60 * 1000); cookie += ';expires=' + date.toGMTString(); }; if (isPlainObject(option)) { if (option.path) cookie += ';path=' + option.path; if (option.domain) cookie += ';domain=' + option.domain; if (option.secure) cookie += ';secure=' + option.secure; }; }; document.cookie = cookie; return cookieParse(); }; export class Sticky { constructor(target, body) { this.target = target; this.body = body; this.position = window.getComputedStyle(this.target).position; this.bind(); this.update(); } update() { if (this.checkIsHit()) { this.target.style.position = this.position; } else { this.target.style.position = 'fixed'; }; } checkIsHit() { const targetRect = this.target.getBoundingClientRect(); const bodyRect = this.body.getBoundingClientRect(); return window.pageYOffset + bodyRect.bottom + targetRect.height > window.innerHeight; } bind() { this.event = () => this.update(); addEventListener(window, this.event, 'resize', 'scroll'); } destroy() { removeEventListener(window, this.event, 'resize', 'scroll'); } }; export const isChildNode = (child, parent) => { if (child === parent) return true; let target = child; while (target && target.nodeType !== 11) { if (target === parent) { return true; } else { target = target.parentNode; }; }; return false; };
shusiwei/tiny
src/node.js
JavaScript
mit
5,044
const {series, crossEnv, concurrent, rimraf} = require('nps-utils') // @if model.integrationTestRunner.id='protractor' const {config: {port : E2E_PORT}} = require('./test/protractor.conf') // @endif module.exports = { scripts: { default: 'nps webpack', test: { // @if testRunners.jest default: 'nps test.jest', // @endif // @if testRunners.jest // @if model.transpiler.id='babel' jest: { default: series( rimraf('test/coverage-jest'), crossEnv('BABEL_TARGET=node jest') ), accept: crossEnv('BABEL_TARGET=node jest -u'), watch: crossEnv('BABEL_TARGET=node jest --watch'), }, // @endif // @if model.transpiler.id='typescript' jest: { default: series( rimraf('test/coverage-jest'), 'jest' ), accept: 'jest -u', watch: 'jest --watch', }, // @endif // @endif // @if testRunners.karma // @if !testRunners.jest default: 'nps test.karma', // @endif karma: { default: series( rimraf('test/coverage-karma'), 'karma start test/karma.conf.js' ), watch: 'karma start test/karma.conf.js --auto-watch --no-single-run', debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug' }, // @endif lint: { default: 'eslint src', fix: 'eslint src --fix' }, all: concurrent({ // @if testRunners.karma // @if testRunners.protractor browser: series.nps('test.karma', 'e2e'), // @endif // @if !testRunners.protractor browser: series.nps('test.karma'), // @endif // @endif // @if !testRunners.karma // @if testRunners.protractor browser: series.nps('e2e'), // @endif // @endif // @if testRunners.jest jest: 'nps test.jest', // @endif lint: 'nps test.lint' }) }, // @if model.integrationTestRunner.id='protractor' e2e: { default: concurrent({ webpack: `webpack-dev-server --inline --port=${E2E_PORT}`, protractor: 'nps e2e.whenReady', }) + ' --kill-others --success first', protractor: { install: 'webdriver-manager update', default: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js' ), debug: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js --elementExplorer' ), }, whenReady: series( `wait-on --timeout 120000 http-get://localhost:${E2E_PORT}/index.html`, 'nps e2e.protractor' ), }, // @endif build: 'nps webpack.build', webpack: { default: 'nps webpack.server', build: { before: rimraf('dist'), default: 'nps webpack.build.production', development: { default: series( 'nps webpack.build.before', 'webpack --progress -d' ), extractCss: series( 'nps webpack.build.before', 'webpack --progress -d --env.extractCss' ), serve: series.nps( 'webpack.build.development', 'serve' ), }, production: { inlineCss: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production') ), default: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss') ), serve: series.nps( 'webpack.build.production', 'serve' ), } }, server: { default: `webpack-dev-server -d --devtool '#source-map' --inline --env.server`, extractCss: `webpack-dev-server -d --devtool '#source-map' --inline --env.server --env.extractCss`, hmr: `webpack-dev-server -d --devtool '#source-map' --inline --hot --env.server` }, }, serve: 'http-server dist --cors', }, }
zewa666/cli
lib/resources/content/package-scripts.template.js
JavaScript
mit
4,186
/** * Print locales settings. * @function print * @param {object} locales - locales settings to print. */ 'use strict' const colorprint = require('colorprint') const yaml = require('js-yaml') function _normalize (data) { switch (typeof data) { case 'number': case 'string': case 'boolean': case 'undefined': return data default: let values = {} for (let key of Object.keys(data)) { let value = _normalize(data[ key ]) if (typeof value === 'undefined') { continue } values[ key ] = value } let isEmpty = Object.keys(values).length === 0 if (isEmpty) { return undefined } return values } } /** @lends print */ function print (locales) { let values = _normalize(locales) colorprint.debug('') colorprint.debug('Locale Settings') colorprint.debug('------------') let msg = yaml.safeDump(values) colorprint.debug(colorprint.colors.blackBright(msg)) colorprint.debug('') colorprint.debug('') } module.exports = print
apeman-labo/apemanlocale
lib/print.js
JavaScript
mit
1,057
import FAnimation from './f-animation' import { left, right } from '../art/art-util' export default class ASleep extends FAnimation { constructor(old) { super(old) this.frames = [this.frame1] } frame1(g, x, y, friendo, blink, words) { // pre-compute constants for drawing for ease of readability const { thighGap } = friendo.element const bodyOffset = friendo.element.bodyOffset - (friendo.element.bodyOffset * 0.1) const legBrush = friendo.element.legBrush(friendo) const armBrush = friendo.element.armBrush(friendo) const armOffset = { x: friendo.element.armOffset.xOffset, y: friendo.element.legHeight - friendo.element.armOffset.yOffset, } const armAngle = 0.15 // pi radians left(g, x - thighGap, y, legBrush) // left leg right(g, x + thighGap, y, legBrush) // right leg left(g, x - armOffset.x, y - armOffset.y, armBrush, armAngle)// left arm right(g, x + armOffset.x, y - armOffset.y, armBrush, armAngle)// right arm const computedTethers = friendo.element.drawCore(g, x, y - bodyOffset, friendo, true) if (words) { friendo.element.speak(g, x + computedTethers.speech.x, computedTethers.speech.y, words) } } }
mattdelsordo/friendo
src/friendo/animation/sleep.js
JavaScript
mit
1,215
(function ($, SmallGrid) { "use strict"; $.extend(true, SmallGrid, { "Column": { "Create": CreateModel, "Model": ColumnModel, "ColumnData": ColumnData } }); function ColumnData() { } ColumnData.prototype.align = "";//column cells align - "" / center / right ColumnData.prototype.cellCssClass = "";//css class for column cells ColumnData.prototype.editable = true; //true when column cells editable ColumnData.prototype.editor = undefined; // name of editor ColumnData.prototype.editMode = false; //true when column cell in editMode ColumnData.prototype.field = ""; //cell content will be taken from value of this property in row ColumnData.prototype.filterable = false;//true when column is filterable ColumnData.prototype.formatter = "Default";//default cell content formatter ColumnData.prototype.headerFormatter = "Default";//default header cell content formatter ColumnData.prototype.headerCssClass = "";//css class for column header cell ColumnData.prototype.hidden = false;//true when column is visible ColumnData.prototype.id = undefined;//column unique indicator ColumnData.prototype.item = null; ColumnData.prototype.maxWidth = 9999; ColumnData.prototype.minWidth = 25; ColumnData.prototype.name = "";//column title in grid header ColumnData.prototype.resizeable = true;//true when column resizeable ColumnData.prototype.sortable = true;//true when column sortable ColumnData.prototype.sortComparer = "Default"; ColumnData.prototype.sortOrder = 0;//0, 1, -1 ColumnData.prototype.width = 50; function ColumnModel(settings) { var self = this; var data = []; this.items = { addItem: function (item) { addColumn(createColumn(item)); return self; }, addItems: function (items) { if (items.length) { self.onChange.lock(); for (var i = 0, len = items.length; i < len; i++) { self.items.addItem(items[i]); } self.onChange.notifyLocked(); } return self; }, deleteItems: function () { return deleteColumns(); }, deleteItemById: function (id) { return deleteColumnById(id); }, getItems: function () { var result = []; for (var i = 0, len = data.length; i < len; i++) { result.push(data[i].item); } return result; }, setItems: function (items) { if (items.length) { self.onChange.lock(); data = []; for (var i = 0, len = items.length; i < len; i++) { self.items.addItem(items[i]); } self.onChange.notifyLocked(); } return self; }, updateItemById: function (id, item) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { data[i].item = item; self.onChange.notify({ "id": id }); break; } } return self; }, updateItemByIndex: function (idx, item) { if (data[idx]) { data[idx].item = item; self.onChange.notify({ "id": data[idx].id }); } return self; } }; function destroy() { data = []; } function filter(callback) { if (data.length) { return data.filter(callback); } return []; } function reduce(callback, initialValue) { if (data.length) { return data.reduce(callback, initialValue); } } function sort(comparer) { if (data.length) { data.sort(comparer); } return self; } function isEmpty() { return data.length === 0; } function total() { return data.length; } function addColumn(column) { if (column instanceof ColumnData) { data.push(column); self.onChange.notify({ "id": column.id }); } return self; } function addColumns(columns) { if (columns.length) { self.onChange.lock(); for (var i = 0, len = columns.length; i < len; i++) { addColumn(columns[i]); } self.onChange.notifyLocked(); } return self; } function deleteColumn(column) { if (column instanceof ColumnData) { deleteColumnById(column.id); } return self; } function deleteColumnById(id) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { data.splice(i, 1); self.onChange.notify({ "id": id }); break; } } return self; } function deleteColumnByIndex(idx) { if (data[idx]) { var id = data[idx].id; data.splice(idx, 1); self.onChange.notify({ "id": id }); } return self; } function deleteColumns() { if (data.length) { self.onChange.lock(); data = []; self.onChange.notifyLocked(); } return self; } function getColumnById(id) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { return data[i]; } } } function getColumnByIndex(idx) { return data[idx]; } function getColumnIdByIndex(idx) { return data[idx].id; } function getColumnIndexById(id) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { return i; } } return -1; } function getColumnPropertyById(id, propertyName) { var column = getColumnById(id); if (column && propertyName && propertyName in column) { return column[propertyName]; } } function getColumnPropertyByIndex(idx, propertyName) { var column = getColumnByIndex(idx); if (column && propertyName && propertyName in column) { return column[propertyName]; } } function getColumns() { return data; } function insertColumnAfterId(id, column) { insertColumnAfterIndex( getColumnIndexById(id), column ); return self; } function insertColumnAfterIndex(idx, column) { if (column instanceof ColumnData) { data.splice( idx + 1, 0, column ); self.onChange.notify({ "id": column.id }); } return self; } function insertColumnBeforeId(id, column) { insertColumnBeforeIndex( getColumnIndexById(id), column ); return self; } function insertColumnBeforeIndex(idx, column) { if (column instanceof ColumnData) { data.splice( idx, 0, column ); self.onChange.notify({ "id": column.id }); } return self; } function setColumnPropertyById(id, propertyName, propertyValue) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { if (propertyName) { data[i][propertyName] = propertyValue; self.onChange.notify({ "id": id }); } break; } } return self; } function setColumnPropertyByIndex(idx, propertyName, propertyValue) { if (propertyName && data[idx]) { data[idx][propertyName] = propertyValue; self.onChange.notify({ "id": data[idx].id }); } return self; } function setColumns(columns) { if (columns.length) { self.onChange.lock(); data = []; for (var i = 0, len = columns.length; i < len; i++) { addColumn(columns[i]); } self.onChange.notifyLocked(); } return self; } function setColumnsProperty(propertyName, propertyValue) { self.onChange.lock(); for (var i = 0, len = data.length; i < len; i++) { data[i][propertyName] = propertyValue; self.onChange.notify({ "id": data[i].id }); } self.onChange.notifyLocked(); return self; } function updateColumn(column) { if (column instanceof ColumnData) { updateColumnById(column.id, column); } return self; } function updateColumnById(id, column) { if (column instanceof ColumnData) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { data[i] = column; self.onChange.notify({ "id": id }); break; } } } return self; } function updateColumnByIndex(idx, column) { if (column instanceof ColumnData) { if (data[idx]) { data[idx] = column; self.onChange.notify({ "id": column.id }); } } return self; } function updateColumns(columns) { if (columns.length) { self.onChange.lock(); for (var i = 0, len = columns.length; i < len; i++) { updateColumn(columns[i]); } self.onChange.notifyLocked(); } return self; } function createColumn(item) { if (item instanceof Object) { var column = new ColumnData(); if (SmallGrid.Utils.isProperty(settings.columns.idProperty, column)) { column.id = column[settings.columns.idProperty]; } else if (settings.columns.newIdType === "number") { column.id = SmallGrid.Utils.createId(); } else { column.id = SmallGrid.Utils.createGuid(); } column.name = item.name; column.field = item.field; column.item = item; if ("align" in item) column.align = item.align; if ("cellCssClass" in item) column.cellCssClass = item.cellCssClass; if ("editable" in item) column.editable = item.editable; if ("editor" in item) column.editor = item.editor; if ("editMode" in item) column.editMode = item.editMode; if ("filterable" in item) column.filterable = item.filterable; if ("formatter" in item) column.formatter = item.formatter; if ("headerFormatter" in item) column.headerFormatter = item.headerFormatter; if ("headerCssClass" in item) column.headerCssClass = item.headerCssClass; if ("hidden" in item) column.hidden = item.hidden; if ("maxWidth" in item) column.maxWidth = item.maxWidth; if ("minWidth" in item) column.minWidth = item.minWidth; if ("resizeable" in item) column.resizeable = item.resizeable; if ("sortable" in item) column.sortable = item.sortable; if ("sortOrder" in item) column.sortOrder = item.sortOrder; if ("sortComparer" in item) column.sortComparer = item.sortComparer; if ("width" in item) column.width = item.width; return column; } } $.extend(this, { "destroy": destroy, "onChange": SmallGrid.Callback.Create(), "filter": filter, "reduce": reduce, "sort": sort, "total": total, "addColumn": addColumn, "addColumns": addColumns, "createColumn": createColumn, "deleteColumn": deleteColumn, "deleteColumnById": deleteColumnById, "deleteColumnByIndex": deleteColumnByIndex, "deleteColumns": deleteColumns, "getColumnById": getColumnById, "getColumnByIndex": getColumnByIndex, "getColumnIdByIndex": getColumnIdByIndex, "getColumnIndexById": getColumnIndexById, "getColumnPropertyById": getColumnPropertyById, "getColumnPropertyByIndex": getColumnPropertyByIndex, "getColumns": getColumns, "insertColumnAfterId": insertColumnAfterId, "insertColumnAfterIndex": insertColumnAfterIndex, "insertColumnBeforeId": insertColumnBeforeId, "insertColumnBeforeIndex": insertColumnBeforeIndex, "isEmpty": isEmpty, "setColumnPropertyById": setColumnPropertyById, "setColumnPropertyByIndex": setColumnPropertyByIndex, "setColumns": setColumns, "setColumnsProperty": setColumnsProperty, "updateColumn": updateColumn, "updateColumnById": updateColumnById, "updateColumnByIndex": updateColumnByIndex, "updateColumns": updateColumns }); } function CreateModel(data, settings) { if (Array.isArray(data) === false) { throw new TypeError("Data is not defined"); } if (settings instanceof Object === false) { throw new TypeError("Settings is not defined"); } return new ColumnModel(settings).items.addItems(data); } })(jQuery, window.SmallGrid = window.SmallGrid || {});
truehot/smallGrid
core/column.js
JavaScript
mit
15,058
'use strict'; class BookRecommendation extends React.Component { constructor(props) { super(props); // this.state = {count: props.initialCount}; } render() { return ( <div> <BookPicture {...this.props} horizontal={true} /> <div className='switch'> <label> <input type='checkbox' onClick={this.props.onSwitch} /> <span className='lever'></span> </label> </div> </div> ); } }
kar288/exquery
hello/static/src/bookRecommendation.js
JavaScript
mit
480
import React from "react"; import { connect } from "react-redux"; import InviteNew from "./view"; import { selectUserInvitesRemaining, selectUserInviteNewIsPending, selectUserInviteNewErrorMessage, } from "redux/selectors/user"; import rewards from "rewards"; import { makeSelectRewardAmountByType } from "redux/selectors/rewards"; import { doUserInviteNew } from "redux/actions/user"; const select = state => { const selectReward = makeSelectRewardAmountByType(); return { errorMessage: selectUserInviteNewErrorMessage(state), invitesRemaining: selectUserInvitesRemaining(state), isPending: selectUserInviteNewIsPending(state), rewardAmount: selectReward(state, { reward_type: rewards.TYPE_REFERRAL }), }; }; const perform = dispatch => ({ inviteNew: email => dispatch(doUserInviteNew(email)), }); export default connect(select, perform)(InviteNew);
jsigwart/lbry-app
src/renderer/js/component/inviteNew/index.js
JavaScript
mit
886
import { OHIF } from 'meteor/ohif:core'; import { _ } from 'meteor/underscore'; // TODO: change this to a const after refactoring newMeasurements code on measurementTableView.js OHIF.measurements.getLocation = collection => { for (let i = 0; i < collection.length; i++) { if (collection[i].location) { return collection[i].location; } } }; /** * Group all measurements by its tool group and measurement number. * * @param measurementApi * @param timepointApi * @returns {*} A list containing each toolGroup and an array containing the measurement rows */ OHIF.measurements.getMeasurementsGroupedByNumber = (measurementApi, timepointApi) => { const getPath = OHIF.utils.ObjectPath.get; const configuration = OHIF.measurements.MeasurementApi.getConfiguration(); if (!measurementApi || !timepointApi || !configuration) return; // Check which tools are going to be displayed const displayToolGroupMap = {}; const displayToolList = []; configuration.measurementTools.forEach(toolGroup => { displayToolGroupMap[toolGroup.id] = false; toolGroup.childTools.forEach(tool => { const willDisplay = !!getPath(tool, 'options.measurementTable.displayFunction'); if (willDisplay) { displayToolList.push(tool.id); displayToolGroupMap[toolGroup.id] = true; } }); }); // Create the result object const groupedMeasurements = []; const baseline = timepointApi.baseline(); if (!baseline) return; configuration.measurementTools.forEach(toolGroup => { // Skip this tool group if it should not be displayed if (!displayToolGroupMap[toolGroup.id]) return; // Retrieve all the data for this Measurement type (e.g. 'targets') // which was recorded at baseline. const atBaseline = measurementApi.fetch(toolGroup.id, { timepointId: baseline.timepointId }); // Obtain a list of the Measurement Numbers from the // measurements which have baseline data const numbers = atBaseline.map(m => m.measurementNumber); // Retrieve all the data for this Measurement type which // match the Measurement Numbers obtained above const data = measurementApi.fetch(toolGroup.id, { toolId: { $in: displayToolList }, measurementNumber: { $in: numbers } }); // Group the Measurements by Measurement Number const groupObject = _.groupBy(data, entry => entry.measurementNumber); // Reformat the data for display in the table const measurementRows = Object.keys(groupObject).map(key => ({ measurementTypeId: toolGroup.id, measurementNumber: key, location: OHIF.measurements.getLocation(groupObject[key]), responseStatus: false, // TODO: Get the latest timepoint and determine the response status entries: groupObject[key] })); // Add the group to the result groupedMeasurements.push({ toolGroup, measurementRows }); }); return groupedMeasurements; };
NucleusIo/HealthGenesis
viewerApp/Packages/ohif-measurements/client/lib/getMeasurementsGroupedByNumber.js
JavaScript
mit
3,251
function MemberExpression(_path) { VISITOR.memberExpression(_path.node); } module.exports = MemberExpression;
seraum/nectarjs
compiler/native/visitor/plugin/MemberExpression.js
JavaScript
mit
113
'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('respec:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ 'skip-install': true }) .withPrompt({ someOption: true }) .on('end', done); }); it('creates files', function () { assert.file([ 'index.html', 'package.json', '.editorconfig' ]); }); });
adrianba/generator-respec
test/test-app.js
JavaScript
mit
595
const renderWay = require('../renderWay'); const way = require('senseway'); module.exports = (model, dispatch) => { // Trim context to history size const context = way.last(model.history, model.contextDistance); return renderWay(context, { label: 'context', numbers: true, numbersBegin: model.history[0].length - model.contextDistance }); };
axelpale/lately
example/drummer/src/contextViewer/render.js
JavaScript
mit
364
'use strict'; const passport = require('passport'); const BearerStrategy = require('passport-http-bearer').Strategy; const ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy; const moment = require('moment'); const OauthClient = require('../src/models/oauth-client'); const Token = require('../src/models/token'); const User = require('../src/models/user'); passport.use(new BearerStrategy( (token, done) => { Token.where({ token, type: 'access_token' }) .where('expires_in', '>', moment().toDate()) .fetch({ withRelated: ['user'] }).then((token, err) => { if (err) return done(err); if (!token) return done(null, false); return done(null, token.toJSON().user, { scope: 'all' }); }); } )); passport.use(new ClientPasswordStrategy( (clientId, clientSecret, done) => { OauthClient.where({ client_id: clientId }).fetch() .then((oauthClient, err) => { if (err) return done(err); if (!oauthClient) { return done({ message: 'Wrong client.' }, false); } if (oauthClient.get('client_secret') != clientSecret) { return done(null, false); } return done(null, oauthClient); }); } ));
kvnbai/revtrial
expressbookshelftrial/lib/passport.js
JavaScript
mit
1,181
/** * * User: lin * Date: 13-11-28 * Time: 下午10:34 * */ var burnrate = window.burnrate = { type_card: { employee: 'employee', skill:'skill'}, title: { Engineer: 'Engineer', Manager:'Manager', vp: 'Vice President', Contractor: 'Contractor'}, skill_type: { department: 'department', title: 'title'}, department: { hr: 'human resource', sales:'sales', development: 'development', finance: 'finance'}, target_type: {'self':'self', 'other one':'other one'}, ability: { _0: 0, _1: 1,_2: 2, _3: 3}, burn: { _1: 1, _2: 2, _3 : 3}, project_level:{ _1: 1, _2: 2, _3 : 3, _4 : 4}, money_funding:{ _5: 5, _10: 10, _15: 15, _20: 20}, vp_num: { _0: 0, _2: 2, _3: 3}, game: {}, init: function(){ initEmployees(); initPlayers(); initSkills(); } }; /** * support zh_cn */ (function lang_zh(burnrate){ _.extend(burnrate, { title_ZH_CN: { Engineer: '工程师', Manager:'经理', vp: '副总裁', Contractor: '外包工程师'}, department_ZH_CN: { hr: '人力资源部', sales:'市场部', development: '研发部',finance: '融资部'}, getTitle_ZH_CN: function (title){ return burnrate.title_ZH_CN[getKey(burnrate.title, title)] || ''; }, getDepartment_ZH_CN: function (department){ return burnrate.department_ZH_CN[getKey(burnrate.department, department)] || ''; } }) })(burnrate); function Game(){ this.players = []; this.employeeCards = []; this.skillCards = []; this.addPlayer = function(player){ this.players.push(player); } } function Project(proejctId, project_level){ this.proejctId = proejctId; this.project_level = project_level; } function Player(id, name, money){ this.id = id; this.name = name; this.money = money; this.projects = []; this.employees = []; this.firing = false;//firing doubles cost //Todo: should not count every time, change to add/min it when employee/fire this.getDepartmentAbility = function (department){ //default ability = zero; var ability = burnrate.ability._0; _.each(this.employees, function(){ var employee = this; if(employee.department == department){ //vp's ability = department's ability,ignore managers if(employee.title == burnrate.title.vp){ ability = employee.ability; }else{ ability = _.max(employee.ability, ability); } } }); return ability; } this.getVPNum = function(){ var vp_num = 0; _.each(this.employees, function(){ var employee = this; if(employee.department == department){ if(employee.title == burnrate.title.vp){ vp_num++; } } }); return vp_num; } this.employ = function(anEmployee){ this.employees.push(anEmployee); } this.fire = function(anEmployee){ this.employees = _.without(this.employees, anEmployee); } this.badIdea = function(project){ this.projects.push(project); } this.release = function(project){ this.projects = _.without(this.projects, project); } } function initPlayers(){ } function Employee(department, ability, title, burn){ this.department = department; this.ability = ability; this.title = title; this.burn = burn; this.toString = function (){ var string = []; string.push('department' + ':' + this.department); string.push('title' + ':' + this.title); string.push('ability' + ':' + this.ability); string.push('burn' + ':' + this.burn); return '[An Employee:{' + string + '}]'; } } function initEmployees(){ var employees = burnrate.employees = {}; //(vp + manager) in every department var abilities = [burnrate.ability._1, burnrate.ability._1, burnrate.ability._2]; var burns = [burnrate.burn._1, burnrate.burn._1, burnrate.burn._2]; for(var department in burnrate.department){ var c_e_d = employees[burnrate.department[department]] = []; //vp br:2 + abi:3 c_e_d.push(new Employee(burnrate.department[department], burnrate.ability._3, burnrate.title.vp,burnrate.burn._2)); //vp br:2 + abi:2 c_e_d.push(new Employee(burnrate.department[department], burnrate.ability._2, burnrate.title.vp,burnrate.burn._2)); c_e_d.push(new Employee(burnrate.department[department], burnrate.ability._2, burnrate.title.vp,burnrate.burn._2)); //vp br:2 + abi:0 c_e_d.push(new Employee(burnrate.department[department], burnrate.ability._0, burnrate.title.vp,burnrate.burn._2)); _.times(10,function(){ //manager br:random[1, 2] + abi:random[1, 2] c_e_d.push(new Employee(burnrate.department[department], abilities[_.random(0,abilities.length)], burnrate.title.Manager, burns[_.random(0,burns.length)])); }); } //Engineer * 15, br:1 + abi:'' _.times(15,function(){ employees[burnrate.department.development].push(new Employee(burnrate.department[department], '', burnrate.title.Engineer, burnrate.burn._1)); }); //Contractor * 15, br:3 + abi:'' _.times(15,function(){ employees[burnrate.department.development].push(new Employee('', '', burnrate.title.Contractor, burnrate.burn._3)); }); } function Skill(name, department, ability, vp_num, skill_type, target_type, affect, note){ this.name = name; this.department = department; this.ability = ability; this.vp_num = vp_num; this.affect = affect; this.note = note; this.skill_type = skill_type; this.target_type = target_type; //Todo:should change to a vari [condition] this.canAffect = function(self, target){ target = (this.target_type == burnrate.target_type.self) ? self : target; if(target_type == burnrate.skill_type.department){ return target.getDepartmentAbility(department) >= this.ability; }else{ return target.getVPNum() >= this.vp_num; } } } function initSkills(){ var skills = []; var bad_idea = new BadIdea(burnrate.ability._2, burnrate.project_level._3); } function test(){ var bad_idea = new BadIdea(burnrate.ability._2, burnrate.project_level._3); var player1 = new Player('player 1', 'me', 100); var player2 = new Player('player 2', 'u', 100); bad_idea.affect(player2) var release = new Release(burnrate.ability._2); log(a = new Release(2)) log(release.canAffect(player2, player2)); release.affect(player2, player2.projects[0]); log(player2); } function BadIdea(ability, level){ burnrate.projectId = 100; var affect = function(target){ var project = new Project(burnrate.projectId++, level); target.badIdea(project); }; BadIdea.prototype = new Skill('Bad Idea', burnrate.department.sales, ability, burnrate.vp_num._0, burnrate.skill_type.department, burnrate.target_type.other_one, affect,''); } function Release(ability){ var affect = function(target, project){ target.release(project); }; Release.prototype = new Skill('Release', burnrate.department.development, ability, burnrate.vp_num._0, burnrate.skill_type.department, burnrate.target_type.self, affect,''); } //hr:网罗,雇错人,雇佣,解雇 //develop:终止 //finance: +5 +10 +15 +20 //market:馊主意 //other:大裁员,解甲归田 $(function(){ burnrate.init(); var $card_border = $(".card-border").remove(); var colors = {}; colors[burnrate.department.development] = 'color-develop'; colors[burnrate.department.hr] = 'color-hr'; colors[burnrate.department.finance] = 'color-finance'; colors[burnrate.department.sales] = 'color-sales'; colors['contractor'] = 'color-contractor'; var names = ['Bill Gates', 'Hans Weich', 'Brad Duke'];//Todo : more names var employees = burnrate.employees; _.each(employees, function(employees_dep, department){ var department_ZH_CN = burnrate.getDepartment_ZH_CN(department); var color = colors[department]; var title_vp = burnrate.title.vp; var title_engineer = burnrate.title.Engineer; var title_outsource = burnrate.title.Contractor; _.each(employees_dep,function(employee){ var ability = employee.ability; var title = employee.title; var title_ZH_CN = burnrate.getTitle_ZH_CN(title); var sign_vp = (title == title_vp) ? 'vp' : ''; var burn_num = employee.burn; var name_employee = names[_.random(names.length)]; var $employeeCard = $card_border.clone() .find(".card").addClass(color).end() .find(".circle").addClass(color + '-light') .addClass('border-' + color).html(ability).end() .find(".department-en").html(department).end() //.toLocaleUpperCase() .find(".department-zh").html(department_ZH_CN).end() .find(".vp").html(sign_vp).end() .find(".title-en").html(title).end() .find(".title-zh").html(title_ZH_CN).end() //.find(".pic").end() TODO: change pic .find(".name-employee").html(name_employee).end() .find(".burn-num").html(burn_num).end(); if(title == title_engineer){ $employeeCard.find(".circle").hide(); }else if(title == title_outsource){ $employeeCard.find(".circle").hide(); $employeeCard.find(".card").removeClass(color).addClass(colors['contractor']); } $(document.body).append($employeeCard); }); }); });
codetilldie/burnrate
frontend/js/burnrate.js
JavaScript
mit
10,116
require.ensure([], function(require) { require("./91.async.js"); require("./183.async.js"); require("./367.async.js"); require("./733.async.js"); }); module.exports = 734;
skeiter9/javascript-para-todo_demo
webapp/node_modules/webpack/benchmark/fixtures/734.async.js
JavaScript
mit
171
// https://leetcode-cn.com/problems/max-area-of-island/ /** * @param {number[][]} grid * @return {number} */ var maxAreaOfIsland = function(grid) { let res = 0; for(let i = 0; i < grid.length; i++) { const row = grid[i]; for (let j = 0; j < row.length; j++) { const visitedArr = initVisitedArr(grid); const temp = dfs(i, j, visitedArr, grid, 0); res = Math.max(res, temp); } } return res; }; console.log(maxAreaOfIsland([[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]])); function dfs(i, j, visitedArr, grid, length) { if ((i >= 0 && j >=0 && i < grid.length && j < grid[0].length) && !visitedArr[i][j] && grid[i][j]) { visitedArr[i][j] = 1; length++; length += dfs(i, j - 1, visitedArr, grid, 0); length += dfs(i + 1, j, visitedArr, grid, 0); length += dfs(i, j + 1, visitedArr, grid, 0); length += dfs(i - 1, j, visitedArr, grid, 0); } return length; } function initVisitedArr(grid) { let visitedArr = []; for(let i = 0; i < grid.length; i++) { const row = grid[i]; visitedArr[i] = []; for (let j = 0; j < row.length; j++) { visitedArr[i][j] = 0; } } return visitedArr; }
bmxklYzj/LeetCode
2017/695/1.js
JavaScript
mit
1,182
version https://git-lfs.github.com/spec/v1 oid sha256:69a4d244efeaa1426b857449a59b971adabfbcf56d804be72cfd6aca1f3017d7 size 26909
yogeshsaroya/new-cdnjs
ajax/libs/ace/1.1.9/mode-scala.js
JavaScript
mit
130
import Grid from './Grid'; import Row from './Row'; import Column from './Column'; export { Grid, Row, Column };
ParmenionUX/parmenion-library
src/components/Layout/Grid/index.js
JavaScript
mit
114
import React from 'react'; import Home from '../../../src/routes/Home/'; import Search from '../../../src/containers/SearchContainer/'; import Repositories from '../../../src/containers/RepositoriesContainer/'; import { shallow } from 'enzyme'; describe('(Route) Home', () => { let wrapper; beforeEach(() => { wrapper = shallow(<Home />); }); it('renders successfully', () => { expect(wrapper).to.have.length(1); }); it('renders a SearchContainer', () => { expect(wrapper.find(Search)).to.have.length(1); }); it('renders a RepositoriesContainer', () => { expect(wrapper.find(Repositories)).to.have.length(1); }); });
DeloitteDigitalUK/react-redux-starter-app
tests/routes/Home/Home.spec.js
JavaScript
mit
656
#!/usr/bin/env node 'use strict'; var dot = require('dot'); var defaults = require('defaults'); var fs = require('fs'); var path = require('path'); var rat = require('rat'); var options = defaults({ strip: false, selfcontained: true }, dot.templateSettings); var licenses = {}; rat.ls(path.resolve(__dirname, './licenses'), function(err, files) { if (err) { return; } var expected = files.length - 1; files.forEach(function(file) { var license = path.basename(file.path, '.txt'); fs.readFile(file.path, 'utf8', function(err, data) { if (err) { return; } licenses[license] = dot.template(data, options).toString().replace('anonymous', license); if (--expected <= 0) { var out = 'module.exports = {'; Object.keys(licenses).forEach(function(license, idx, array) { out += license + ':' + licenses[license]; if (idx < array.length - 1) { out += ','; } }); out += '}'; fs.writeFile(path.resolve(__dirname, './lib/licenses.js'), out, 'utf8', function(err) { if (err) { return; } }); } }); }); });
adoyle-h/gulp-license
build.js
JavaScript
mit
1,069
webpackJsonp([0,1],[ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(1); __webpack_require__(3); __webpack_require__(13); __webpack_require__(15); __webpack_require__(28); __webpack_require__(30); __webpack_require__(32); console.log('src'); /***/ }, /* 1 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 2 */, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(4); __webpack_require__(5); __webpack_require__(7); __webpack_require__(9); __webpack_require__(11); /***/ }, /* 4 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(6); /***/ }, /* 6 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(8); /***/ }, /* 8 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(10); /***/ }, /* 10 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(12); /***/ }, /* 12 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(14); console.log('data'); /***/ }, /* 14 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(16); __webpack_require__(17); __webpack_require__(19); __webpack_require__(21); __webpack_require__(23); __webpack_require__(26); console.log('form'); /***/ }, /* 16 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(18); /***/ }, /* 18 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(20); /***/ }, /* 20 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(22); /***/ }, /* 22 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(24); var _basic = __webpack_require__(25); var _basic2 = _interopRequireDefault(_basic); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var $ = _basic2.default.$; var $$ = _basic2.default.$$; var inputNum = $$('.g-input--num'); var input = $('input', inputNum); var min = $('.min', inputNum); var plus = $('.plus', inputNum); input.forEach(function (item) { item.dataset.counter = item.value = 0; item.addEventListener('input', function () { var oldVal = item.value; item.value = parseInt(oldVal.replace(/[^\d]/g, ''), 10) || 0; }); item.addEventListener('keyup', function (e) { var keyCode = e.keyCode; if (keyCode != _basic2.default.keyCode.up && keyCode != _basic2.default.keyCode.down) { return; } var curCounter = parseInt(item.dataset.counter, 10); var maxValue = item.dataset.max || 0; var max = parseInt(maxValue, 10); var stepValue = item.dataset.step || 1; var step = parseInt(stepValue, 10); if (keyCode == _basic2.default.keyCode.up) { if (max > 0 && curCounter >= max) { return; } var newVal = curCounter + step; if (max > 0 && newVal > max) { newVal = max; } item.dataset.counter = item.value = newVal; } else if (keyCode == _basic2.default.keyCode.down) { if (curCounter !== 0) { var _newVal = curCounter - step; if (_newVal < 0) { _newVal = 0; } item.dataset.counter = item.value = _newVal; } } }); }); min.forEach(function (item) { var parent = item.parentNode; var input = $('input', parent); item.addEventListener('click', function () { var curCounter = parseInt(input.dataset.counter, 10); var stepValue = input.dataset.step || 1; var step = parseInt(stepValue, 10); if (curCounter !== 0) { var newVal = curCounter - step; if (newVal < 0) { newVal = 0; } input.dataset.counter = input.value = newVal; } }); }); plus.forEach(function (item) { var parent = item.parentNode; var input = $('input', parent); item.addEventListener('click', function () { var curCounter = parseInt(input.dataset.counter, 10); var maxValue = input.dataset.max || 0; var max = parseInt(maxValue, 10); var stepValue = input.dataset.step || 1; var step = parseInt(stepValue, 10); if (max > 0 && curCounter >= max) { return; } var newVal = curCounter + step; if (max > 0 && newVal > max) { newVal = max; } input.dataset.counter = input.value = newVal; }); }); console.log(inputNum, input, min, plus); /***/ }, /* 24 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 25 */ /***/ function(module, exports) { '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; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } exports.default = { $: function $(selector) { var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; if (context instanceof NodeList) { return Array.from(context, function (node) { return node.querySelector(selector); }); } return context.querySelector(selector); }, $$: function $$(selector) { var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document; if (context instanceof NodeList) { return Array.from(context, function (node) { return node.querySelectorAll(selector); }); } return context.querySelectorAll(selector); }, create: function create() { var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var node = document.createElement(tagName); for (var key in attrs) { node.setAttribute(key, attrs[key]); } return node; }, attr: function attr(node, _attr) { var newVal = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (newVal) { node.setAttribute(_attr, newVal); return; } return node.getAttribute(_attr); }, attrs: function attrs(node) { var attrs = {}; Array.from(node.attributes).forEach(function (attr) { var attrName = attr.nodeName; attrs[attrName] = node.getAttribute(attrName); }); return attrs; }, class: function _class(node, className) { var remove = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (remove) { node.classList.remove(className); return; } if (Array.isArray(className)) { var _node$classList; (_node$classList = node.classList).add.apply(_node$classList, _toConsumableArray(className)); return; } node.classList.add(className); }, css: function css(node, styles) { node.style.cssText = node.style.cssText ? node.style.cssText += styles : styles; }, vdom: function () { function VDOM() { var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var children = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; _classCallCheck(this, VDOM); this.tagName = tagName; this.attrs = attrs; this.children = Array.isArray(children) ? children : Array.from(children); this.event = []; } _createClass(VDOM, [{ key: 'render', value: function render() { var node = document.createElement(this.tagName); var attrs = this.attrs; for (var attr in attrs) { node.setAttribute(attr, attrs[attr]); } if (this.event.length) { this.event.forEach(function (eachEvent) { node.addEventListener(eachEvent.eventName, eachEvent.callback); }); } var children = this.children; Array.from(children).forEach(function (child) { var childEl = child instanceof VDOM ? child.render() : document.createTextNode(child); node.appendChild(childEl); }); return node; } }, { key: 'addEvent', value: function addEvent(eventName, callback) { this.event.push({ eventName: eventName, callback: callback }); } }]); return VDOM; }(), keyCode: { 'up': 38, 'down': 40 } }; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(27); var _basic = __webpack_require__(25); var _basic2 = _interopRequireDefault(_basic); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var select = _basic2.default.$$('.g-select'); var vdom = _basic2.default.vdom; select.forEach(function (item) { var tmpFragment = document.createDocumentFragment(); var parentNode = item.parentNode; var nodeAttrs = _basic2.default.attrs(item); var options = []; var optionsOriginal = _basic2.default.$$('option', item); var selected = { value: '', text: '' }; var child = void 0; optionsOriginal.forEach(function (child) { var text = child.innerText; var attrs = _basic2.default.attrs(child); if ('selected' in attrs) { selected.text = text; selected.value = attrs['value']; } var listItem = new vdom('li', attrs, [text]); listItem.addEvent('click', function (e) { var li = e.target; var ul = li.parentNode; var parent = ul.parentNode; var input = _basic2.default.$('input', parent); if (_basic2.default.attr(li, 'disabled')) { return; } parent.classList.remove('slideDown'); input.value = li.innerText; _basic2.default.attr(input, 'data-value', _basic2.default.attr(li, 'value')); }); options.push(listItem); }); var selectList = new vdom('ul', {}, options); if (selected.value === '') { selected.text = optionsOriginal[0].innerText; selected.value = optionsOriginal[0].getAttribute('value'); } var input = new vdom('input', { type: 'text', name: nodeAttrs.name, readonly: true, value: selected.text, 'data-value': selected.value }); input.addEvent('click', function (e) { var parent = e.target.parentNode; parent.classList.toggle('slideDown'); }); var node = new vdom('div', { class: 'g-selector' }, [input, selectList]); var nodeRendered = node.render(); parentNode.insertBefore(nodeRendered, item); item.remove(); }); /***/ }, /* 27 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(29); console.log('navigation'); /***/ }, /* 29 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(31); console.log('notice'); /***/ }, /* 31 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(33); console.log('others'); /***/ }, /* 33 */ /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ } ]); //# sourceMappingURL=index.84d6416787a648d52de3.js.map
gongpeione/gecom
docs/js/index.84d6416787a648d52de3.js
JavaScript
mit
14,763
exports.seed = function(knex) { return knex('users_follows').del() .then(() => { return knex('users_follows').insert([{ id: 1, user_id: 2, follow_id: 1, created_at: new Date('2016-06-29 14:26:16 UTC'), updated_at: new Date('2016-06-29 14:26:16 UTC') }]); }) .then(() => { return knex.raw( "SELECT setval('users_id_seq', (SELECT MAX(id) FROM users_follows));" ); }); };
PortableTomb/capstone
seeds/5users_follows.js
JavaScript
mit
459
const {BrowserWindow, ipcMain} = require('electron') const CssInjector = require('../configuration/css-injector'); const path = require('path'); const isOnline = require('is-online'); class RadioController { constructor() { this.initSplash(); setTimeout(() => this.checkConnectionAndStart(), 500); } init() { this.window = new BrowserWindow({ width: 1000, height: 470, show: false, frame: true, autoHideMenuBar: true, webPreferences: { plugins: true }, }); this.window.on('close', (e) => { if (this.window.isVisible()) { e.preventDefault(); this.window.hide(); } }); this.window.loadURL('http://www.xiami.com/radio'); this.window.webContents.on('dom-ready', () => { this.window.webContents.insertCSS(CssInjector.radio); this.show(); }); } show() { this.window.show(); this.window.focus(); } initSplash() { this.splashWin = new BrowserWindow({ width: 300, height: 300, frame: false, autoHideMenuBar: true, webPreferences: { nodeIntegration: true } }); this.splashWin.loadURL(`file://${path.join(__dirname, '../view/splash.html')}`); ipcMain.on('reconnect', () => { this.checkConnectionAndStart(); }); } checkConnectionAndStart() { (async () => await isOnline({timeout: 15000}))().then(result => { if (result) { setTimeout(() => this.init(), 1000); } else { this.splashWin.webContents.send('connect-timeout'); } }); } } module.exports = RadioController;
eNkru/electron-xiami
src/controller/radio-controller.js
JavaScript
mit
1,628
var multilevel = require('multilevel'); var net = require('net'); var db = multilevel.client(); var connection = net.connect(4545); connection.pipe(db.createRpcStream()).pipe(connection); db.get('multilevelmeup', function(err, item) { if(err) throw err; console.log(item); connection.end(); });
zburgermeiszter/nodeschool.io
level-me-up/12_multilevel/program.js
JavaScript
mit
307
(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){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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'); } }; })(); 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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _debounce = require('debounce'); var _debounce2 = _interopRequireDefault(_debounce); var _reactThemeable = require('react-themeable'); var _reactThemeable2 = _interopRequireDefault(_reactThemeable); var _sectionIterator = require('./sectionIterator'); var _sectionIterator2 = _interopRequireDefault(_sectionIterator); var Autosuggest = (function (_Component) { _inherits(Autosuggest, _Component); _createClass(Autosuggest, null, [{ key: 'propTypes', value: { value: _react.PropTypes.string, // Controlled value of the selected suggestion defaultValue: _react.PropTypes.string, // Initial value of the text suggestions: _react.PropTypes.func.isRequired, // Function to get the suggestions suggestionRenderer: _react.PropTypes.func, // Function that renders a given suggestion (must be implemented when suggestions are objects) suggestionValue: _react.PropTypes.func, // Function that maps suggestion object to input value (must be implemented when suggestions are objects) showWhen: _react.PropTypes.func, // Function that determines whether to show suggestions or not onSuggestionSelected: _react.PropTypes.func, // This function is called when suggestion is selected via mouse click or Enter onSuggestionFocused: _react.PropTypes.func, // This function is called when suggestion is focused via mouse hover or Up/Down keys onSuggestionUnfocused: _react.PropTypes.func, // This function is called when suggestion is unfocused via mouse hover or Up/Down keys inputAttributes: _react.PropTypes.object, // Attributes to pass to the input field (e.g. { id: 'my-input', className: 'sweet autosuggest' }) cache: _react.PropTypes.bool, // Set it to false to disable in-memory caching id: _react.PropTypes.string, // Used in aria-* attributes. If multiple Autosuggest's are rendered on a page, they must have unique ids. scrollBar: _react.PropTypes.bool, // Set it to true when the suggestions container can have a scroll bar theme: _react.PropTypes.object // Custom theme. See: https://github.com/markdalgleish/react-themeable }, enumerable: true }, { key: 'defaultProps', value: { showWhen: function showWhen(input) { return input.trim().length > 0; }, onSuggestionSelected: function onSuggestionSelected() {}, onSuggestionFocused: function onSuggestionFocused() {}, onSuggestionUnfocused: function onSuggestionUnfocused() {}, inputAttributes: {}, cache: true, id: '1', scrollBar: false, theme: { root: 'react-autosuggest', suggestions: 'react-autosuggest__suggestions', suggestion: 'react-autosuggest__suggestion', suggestionIsFocused: 'react-autosuggest__suggestion--focused', section: 'react-autosuggest__suggestions-section', sectionName: 'react-autosuggest__suggestions-section-name', sectionSuggestions: 'react-autosuggest__suggestions-section-suggestions' } }, enumerable: true }]); function Autosuggest(props) { _classCallCheck(this, Autosuggest); _get(Object.getPrototypeOf(Autosuggest.prototype), 'constructor', this).call(this); this.cache = {}; this.state = { value: props.value || props.defaultValue || '', suggestions: null, focusedSectionIndex: null, // Used when multiple sections are displayed focusedSuggestionIndex: null, // Index within a section valueBeforeUpDown: null // When user interacts using the Up and Down keys, // this field remembers input's value prior to // interaction in order to revert back if ESC hit. // See: http://www.w3.org/TR/wai-aria-practices/#autocomplete }; this.isControlledComponent = typeof props.value !== 'undefined'; this.suggestionsFn = (0, _debounce2['default'])(props.suggestions, 100); this.onChange = props.inputAttributes.onChange || function () {}; this.onFocus = props.inputAttributes.onFocus || function () {}; this.onBlur = props.inputAttributes.onBlur || function () {}; this.lastSuggestionsInputValue = null; // Helps to deal with delayed requests this.justUnfocused = false; // Helps to avoid calling onSuggestionUnfocused // twice when mouse is moving between suggestions this.justClickedOnSuggestion = false; // Helps not to call inputAttributes.onBlur // and showSuggestions() when suggestion is clicked. // Also helps not to call handleValueChange() in // componentWillReceiveProps() when suggestion is clicked. this.justPressedUpDown = false; // Helps not to call handleValueChange() in // componentWillReceiveProps() when Up or Down is pressed. this.justPressedEsc = false; // Helps not to call handleValueChange() in // componentWillReceiveProps() when ESC is pressed. this.onInputChange = this.onInputChange.bind(this); this.onInputKeyDown = this.onInputKeyDown.bind(this); this.onInputFocus = this.onInputFocus.bind(this); this.onInputBlur = this.onInputBlur.bind(this); } _createClass(Autosuggest, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.isControlledComponent) { var inputValue = this.refs.input.value; if (nextProps.value !== inputValue && !this.justClickedOnSuggestion && !this.justPressedUpDown && !this.justPressedEsc) { this.handleValueChange(nextProps.value); } } } }, { key: 'resetSectionIterator', value: function resetSectionIterator(suggestions) { if (this.isMultipleSections(suggestions)) { _sectionIterator2['default'].setData(suggestions.map(function (suggestion) { return suggestion.suggestions.length; })); } else { _sectionIterator2['default'].setData(suggestions === null ? [] : suggestions.length); } } }, { key: 'isMultipleSections', value: function isMultipleSections(suggestions) { return suggestions !== null && suggestions.length > 0 && typeof suggestions[0].suggestions !== 'undefined'; } }, { key: 'setSuggestionsState', value: function setSuggestionsState(suggestions) { this.resetSectionIterator(suggestions); this.setState({ suggestions: suggestions, focusedSectionIndex: null, focusedSuggestionIndex: null, valueBeforeUpDown: null }); } }, { key: 'suggestionsExist', value: function suggestionsExist(suggestions) { if (this.isMultipleSections(suggestions)) { return suggestions.some(function (section) { return section.suggestions.length > 0; }); } return suggestions !== null && suggestions.length > 0; } }, { key: 'showSuggestions', value: function showSuggestions(input) { var _this = this; var cacheKey = input.toLowerCase(); this.lastSuggestionsInputValue = input; if (!this.props.showWhen(input)) { this.setSuggestionsState(null); } else if (this.props.cache && this.cache[cacheKey]) { this.setSuggestionsState(this.cache[cacheKey]); } else { this.suggestionsFn(input, function (error, suggestions) { // If input value changed, suggestions are not relevant anymore. if (_this.lastSuggestionsInputValue !== input) { return; } if (error) { throw error; } else { if (!_this.suggestionsExist(suggestions)) { suggestions = null; } if (_this.props.cache) { _this.cache[cacheKey] = suggestions; } _this.setSuggestionsState(suggestions); } }); } } }, { key: 'suggestionIsFocused', value: function suggestionIsFocused() { return this.state.focusedSuggestionIndex !== null; } }, { key: 'getSuggestion', value: function getSuggestion(sectionIndex, suggestionIndex) { if (this.isMultipleSections(this.state.suggestions)) { return this.state.suggestions[sectionIndex].suggestions[suggestionIndex]; } return this.state.suggestions[suggestionIndex]; } }, { key: 'getFocusedSuggestion', value: function getFocusedSuggestion() { if (this.suggestionIsFocused()) { return this.getSuggestion(this.state.focusedSectionIndex, this.state.focusedSuggestionIndex); } return null; } }, { key: 'getSuggestionValue', value: function getSuggestionValue(sectionIndex, suggestionIndex) { var suggestion = this.getSuggestion(sectionIndex, suggestionIndex); if (typeof suggestion === 'object') { if (this.props.suggestionValue) { return this.props.suggestionValue(suggestion); } throw new Error('When <suggestion> is an object, you must implement the suggestionValue() function to specify how to set input\'s value when suggestion selected.'); } else { return suggestion.toString(); } } }, { key: 'onSuggestionUnfocused', value: function onSuggestionUnfocused() { var focusedSuggestion = this.getFocusedSuggestion(); if (focusedSuggestion !== null && !this.justUnfocused) { this.props.onSuggestionUnfocused(focusedSuggestion); this.justUnfocused = true; } } }, { key: 'onSuggestionFocused', value: function onSuggestionFocused(sectionIndex, suggestionIndex) { this.onSuggestionUnfocused(); var suggestion = this.getSuggestion(sectionIndex, suggestionIndex); this.props.onSuggestionFocused(suggestion); this.justUnfocused = false; } }, { key: 'scrollToElement', value: function scrollToElement(container, element, alignTo) { if (alignTo === 'bottom') { var scrollDelta = element.offsetTop + element.offsetHeight - container.scrollTop - container.offsetHeight; if (scrollDelta > 0) { container.scrollTop += scrollDelta; } } else { var scrollDelta = container.scrollTop - element.offsetTop; if (scrollDelta > 0) { container.scrollTop -= scrollDelta; } } } }, { key: 'scrollToSuggestion', value: function scrollToSuggestion(direction, sectionIndex, suggestionIndex) { var alignTo = direction === 'down' ? 'bottom' : 'top'; if (suggestionIndex === null) { if (direction === 'down') { alignTo = 'top'; var _sectionIterator$next = _sectionIterator2['default'].next([null, null]); var _sectionIterator$next2 = _slicedToArray(_sectionIterator$next, 2); sectionIndex = _sectionIterator$next2[0]; suggestionIndex = _sectionIterator$next2[1]; } else { return; } } else { if (_sectionIterator2['default'].isLast([sectionIndex, suggestionIndex]) && direction === 'up') { alignTo = 'bottom'; } } var suggestions = this.refs.suggestions; var suggestionRef = this.getSuggestionRef(sectionIndex, suggestionIndex); var suggestion = this.refs[suggestionRef]; this.scrollToElement(suggestions, suggestion, alignTo); } }, { key: 'focusOnSuggestionUsingKeyboard', value: function focusOnSuggestionUsingKeyboard(direction, suggestionPosition) { var _this2 = this; var _suggestionPosition = _slicedToArray(suggestionPosition, 2); var sectionIndex = _suggestionPosition[0]; var suggestionIndex = _suggestionPosition[1]; var newState = { focusedSectionIndex: sectionIndex, focusedSuggestionIndex: suggestionIndex, value: suggestionIndex === null ? this.state.valueBeforeUpDown : this.getSuggestionValue(sectionIndex, suggestionIndex) }; this.justPressedUpDown = true; // When users starts to interact with Up/Down keys, remember input's value. if (this.state.valueBeforeUpDown === null) { newState.valueBeforeUpDown = this.state.value; } if (suggestionIndex === null) { this.onSuggestionUnfocused(); } else { this.onSuggestionFocused(sectionIndex, suggestionIndex); } if (this.props.scrollBar) { this.scrollToSuggestion(direction, sectionIndex, suggestionIndex); } if (newState.value !== this.state.value) { this.onChange(newState.value); } this.setState(newState); setTimeout(function () { return _this2.justPressedUpDown = false; }); } }, { key: 'onSuggestionSelected', value: function onSuggestionSelected(event) { var focusedSuggestion = this.getFocusedSuggestion(); this.props.onSuggestionUnfocused(focusedSuggestion); this.props.onSuggestionSelected(focusedSuggestion, event); } }, { key: 'onInputChange', value: function onInputChange(event) { var newValue = event.target.value; this.onSuggestionUnfocused(); this.handleValueChange(newValue); this.showSuggestions(newValue); } }, { key: 'handleValueChange', value: function handleValueChange(newValue) { if (newValue !== this.state.value) { this.onChange(newValue); this.setState({ value: newValue }); } } }, { key: 'onInputKeyDown', value: function onInputKeyDown(event) { var _this3 = this; var newState = undefined; switch (event.keyCode) { case 13: // Enter if (this.state.valueBeforeUpDown !== null && this.suggestionIsFocused()) { this.onSuggestionSelected(event); this.setSuggestionsState(null); } break; case 27: // ESC newState = { suggestions: null, focusedSectionIndex: null, focusedSuggestionIndex: null, valueBeforeUpDown: null }; if (this.state.valueBeforeUpDown !== null) { newState.value = this.state.valueBeforeUpDown; } else if (this.state.suggestions === null) { newState.value = ''; } this.onSuggestionUnfocused(); this.justPressedEsc = true; if (typeof newState.value === 'string' && newState.value !== this.state.value) { this.onChange(newState.value); } this.setState(newState); setTimeout(function () { return _this3.justPressedEsc = false; }); break; case 38: // Up if (this.state.suggestions === null) { this.showSuggestions(this.state.value); } else { this.focusOnSuggestionUsingKeyboard('up', _sectionIterator2['default'].prev([this.state.focusedSectionIndex, this.state.focusedSuggestionIndex])); } event.preventDefault(); // Prevent the cursor from jumping to input's start break; case 40: // Down if (this.state.suggestions === null) { this.showSuggestions(this.state.value); } else { this.focusOnSuggestionUsingKeyboard('down', _sectionIterator2['default'].next([this.state.focusedSectionIndex, this.state.focusedSuggestionIndex])); } break; } } }, { key: 'onInputFocus', value: function onInputFocus(event) { if (!this.justClickedOnSuggestion) { this.showSuggestions(this.state.value); } this.onFocus(event); } }, { key: 'onInputBlur', value: function onInputBlur(event) { this.onSuggestionUnfocused(); if (!this.justClickedOnSuggestion) { this.onBlur(event); } this.setSuggestionsState(null); } }, { key: 'isSuggestionFocused', value: function isSuggestionFocused(sectionIndex, suggestionIndex) { return sectionIndex === this.state.focusedSectionIndex && suggestionIndex === this.state.focusedSuggestionIndex; } }, { key: 'onSuggestionMouseEnter', value: function onSuggestionMouseEnter(sectionIndex, suggestionIndex) { if (!this.isSuggestionFocused(sectionIndex, suggestionIndex)) { this.onSuggestionFocused(sectionIndex, suggestionIndex); } this.setState({ focusedSectionIndex: sectionIndex, focusedSuggestionIndex: suggestionIndex }); } }, { key: 'onSuggestionMouseLeave', value: function onSuggestionMouseLeave(sectionIndex, suggestionIndex) { if (this.isSuggestionFocused(sectionIndex, suggestionIndex)) { this.onSuggestionUnfocused(); } this.setState({ focusedSectionIndex: null, focusedSuggestionIndex: null }); } }, { key: 'onSuggestionMouseDown', value: function onSuggestionMouseDown(sectionIndex, suggestionIndex, event) { var _this4 = this; var suggestionValue = this.getSuggestionValue(sectionIndex, suggestionIndex); this.justClickedOnSuggestion = true; this.onSuggestionSelected(event); if (suggestionValue !== this.state.value) { this.onChange(suggestionValue); } this.setState({ value: suggestionValue, suggestions: null, focusedSectionIndex: null, focusedSuggestionIndex: null, valueBeforeUpDown: null }, function () { // This code executes after the component is re-rendered setTimeout(function () { _this4.refs.input.focus(); _this4.justClickedOnSuggestion = false; }); }); } }, { key: 'getSuggestionId', value: function getSuggestionId(sectionIndex, suggestionIndex) { if (suggestionIndex === null) { return null; } return 'react-autosuggest-' + this.props.id + '-' + this.getSuggestionRef(sectionIndex, suggestionIndex); } }, { key: 'getSuggestionRef', value: function getSuggestionRef(sectionIndex, suggestionIndex) { return 'suggestion-' + (sectionIndex === null ? '' : sectionIndex) + '-' + suggestionIndex; } }, { key: 'renderSuggestionContent', value: function renderSuggestionContent(suggestion) { if (this.props.suggestionRenderer) { return this.props.suggestionRenderer(suggestion, this.state.valueBeforeUpDown || this.state.value); } if (typeof suggestion === 'object') { throw new Error('When <suggestion> is an object, you must implement the suggestionRenderer() function to specify how to render it.'); } else { return suggestion.toString(); } } }, { key: 'renderSuggestionsList', value: function renderSuggestionsList(theme, suggestions, sectionIndex) { var _this5 = this; return suggestions.map(function (suggestion, suggestionIndex) { var styles = theme(suggestionIndex, 'suggestion', sectionIndex === _this5.state.focusedSectionIndex && suggestionIndex === _this5.state.focusedSuggestionIndex && 'suggestionIsFocused'); var suggestionRef = _this5.getSuggestionRef(sectionIndex, suggestionIndex); return _react2['default'].createElement( 'li', _extends({ id: _this5.getSuggestionId(sectionIndex, suggestionIndex) }, styles, { role: 'option', ref: suggestionRef, key: suggestionRef, onMouseEnter: function () { return _this5.onSuggestionMouseEnter(sectionIndex, suggestionIndex); }, onMouseLeave: function () { return _this5.onSuggestionMouseLeave(sectionIndex, suggestionIndex); }, onMouseDown: function (event) { return _this5.onSuggestionMouseDown(sectionIndex, suggestionIndex, event); } }), _this5.renderSuggestionContent(suggestion) ); }); } }, { key: 'renderSuggestions', value: function renderSuggestions(theme) { var _this6 = this; if (this.state.suggestions === null) { return null; } if (this.isMultipleSections(this.state.suggestions)) { return _react2['default'].createElement( 'div', _extends({ id: 'react-autosuggest-' + this.props.id }, theme('suggestions', 'suggestions'), { ref: 'suggestions', role: 'listbox' }), this.state.suggestions.map(function (section, sectionIndex) { var sectionName = section.sectionName ? _react2['default'].createElement( 'div', theme('sectionName-' + sectionIndex, 'sectionName'), section.sectionName ) : null; return section.suggestions.length === 0 ? null : _react2['default'].createElement( 'div', _extends({}, theme('section-' + sectionIndex, 'section'), { key: 'section-' + sectionIndex }), sectionName, _react2['default'].createElement( 'ul', theme('sectionSuggestions-' + sectionIndex, 'sectionSuggestions'), _this6.renderSuggestionsList(theme, section.suggestions, sectionIndex) ) ); }) ); } return _react2['default'].createElement( 'ul', _extends({ id: 'react-autosuggest-' + this.props.id }, theme('suggestions', 'suggestions'), { ref: 'suggestions', role: 'listbox' }), this.renderSuggestionsList(theme, this.state.suggestions, null) ); } }, { key: 'render', value: function render() { var _props = this.props; var id = _props.id; var inputAttributes = _props.inputAttributes; var _state = this.state; var value = _state.value; var suggestions = _state.suggestions; var focusedSectionIndex = _state.focusedSectionIndex; var focusedSuggestionIndex = _state.focusedSuggestionIndex; var theme = (0, _reactThemeable2['default'])(this.props.theme); var ariaActivedescendant = this.getSuggestionId(focusedSectionIndex, focusedSuggestionIndex); return _react2['default'].createElement( 'div', theme('root', 'root'), _react2['default'].createElement('input', _extends({}, inputAttributes, { type: inputAttributes.type || 'text', value: value, autoComplete: 'off', role: 'combobox', 'aria-autocomplete': 'list', 'aria-owns': 'react-autosuggest-' + id, 'aria-expanded': suggestions !== null, 'aria-activedescendant': ariaActivedescendant, ref: 'input', onChange: this.onInputChange, onKeyDown: this.onInputKeyDown, onFocus: this.onInputFocus, onBlur: this.onInputBlur })), this.renderSuggestions(theme) ); } }]); return Autosuggest; })(_react.Component); exports['default'] = Autosuggest; module.exports = exports['default']; },{"./sectionIterator":2,"debounce":3,"react":163,"react-themeable":5}],2:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); 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'); } }; })(); var data = undefined, multipleSections = undefined; function setData(newData) { data = newData; multipleSections = typeof data === 'object'; } function nextNonEmptySectionIndex(sectionIndex) { if (sectionIndex === null) { sectionIndex = 0; } else { sectionIndex++; } while (sectionIndex < data.length && data[sectionIndex] === 0) { sectionIndex++; } return sectionIndex === data.length ? null : sectionIndex; } function prevNonEmptySectionIndex(sectionIndex) { if (sectionIndex === null) { sectionIndex = data.length - 1; } else { sectionIndex--; } while (sectionIndex >= 0 && data[sectionIndex] === 0) { sectionIndex--; } return sectionIndex === -1 ? null : sectionIndex; } function next(position) { var _position = _slicedToArray(position, 2); var sectionIndex = _position[0]; var itemIndex = _position[1]; if (multipleSections) { if (itemIndex === null || itemIndex === data[sectionIndex] - 1) { sectionIndex = nextNonEmptySectionIndex(sectionIndex); if (sectionIndex === null) { return [null, null]; } return [sectionIndex, 0]; } return [sectionIndex, itemIndex + 1]; } if (data === 0 || itemIndex === data - 1) { return [null, null]; } if (itemIndex === null) { return [null, 0]; } return [null, itemIndex + 1]; } function prev(position) { var _position2 = _slicedToArray(position, 2); var sectionIndex = _position2[0]; var itemIndex = _position2[1]; if (multipleSections) { if (itemIndex === null || itemIndex === 0) { sectionIndex = prevNonEmptySectionIndex(sectionIndex); if (sectionIndex === null) { return [null, null]; } return [sectionIndex, data[sectionIndex] - 1]; } return [sectionIndex, itemIndex - 1]; } if (data === 0 || itemIndex === 0) { return [null, null]; } if (itemIndex === null) { return [null, data - 1]; } return [null, itemIndex - 1]; } function isLast(position) { return next(position)[1] === null; } exports['default'] = { setData: setData, next: next, prev: prev, isLast: isLast }; module.exports = exports['default']; },{}],3:[function(require,module,exports){ /** * Module dependencies. */ var now = require('date-now'); /** * Returns a function, that, as long as it continues to be invoked, will not * be triggered. The function will be called after it stops being called for * N milliseconds. If `immediate` is passed, trigger the function on the * leading edge, instead of the trailing. * * @source underscore.js * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ * @param {Function} function to wrap * @param {Number} timeout in ms (`100`) * @param {Boolean} whether to execute at the beginning (`false`) * @api public */ module.exports = function debounce(func, wait, immediate){ var timeout, args, context, timestamp, result; if (null == wait) wait = 100; function later() { var last = now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function debounced() { context = this; args = arguments; timestamp = now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; },{"date-now":4}],4:[function(require,module,exports){ module.exports = Date.now || now function now() { return new Date().getTime() } },{}],5:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } } var _objectAssign = require('object-assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var truthy = function truthy(x) { return x; }; exports['default'] = function (theme) { return function (key) { for (var _len = arguments.length, names = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { names[_key - 1] = arguments[_key]; } var styles = names.map(function (name) { return theme[name]; }).filter(truthy); return typeof styles[0] === 'string' ? { key: key, className: styles.join(' ') } : { key: key, style: _objectAssign2['default'].apply(undefined, [{}].concat(_toConsumableArray(styles))) }; }; }; module.exports = exports['default']; },{"object-assign":6}],6:[function(require,module,exports){ 'use strict'; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function ownEnumerableKeys(obj) { var keys = Object.getOwnPropertyNames(obj); if (Object.getOwnPropertySymbols) { keys = keys.concat(Object.getOwnPropertySymbols(obj)); } return keys.filter(function (key) { return propIsEnumerable.call(obj, key); }); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = ownEnumerableKeys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; },{}],7:[function(require,module,exports){ 'use strict'; module.exports = require('react/lib/ReactDOM'); },{"react/lib/ReactDOM":42}],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 AutoFocusUtils * @typechecks static-only */ 'use strict'; var ReactMount = require('./ReactMount'); var findDOMNode = require('./findDOMNode'); var focusNode = require('fbjs/lib/focusNode'); var Mixin = { componentDidMount: function () { if (this.props.autoFocus) { focusNode(findDOMNode(this)); } } }; var AutoFocusUtils = { Mixin: Mixin, focusDOMComponent: function () { focusNode(ReactMount.getNode(this._rootNodeID)); } }; module.exports = AutoFocusUtils; },{"./ReactMount":72,"./findDOMNode":115,"fbjs/lib/focusNode":145}],9:[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('fbjs/lib/ExecutionEnvironment'); var FallbackCompositionState = require('./FallbackCompositionState'); var SyntheticCompositionEvent = require('./SyntheticCompositionEvent'); var SyntheticInputEvent = require('./SyntheticInputEvent'); var keyOf = require('fbjs/lib/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, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(topLevelTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; },{"./EventConstants":21,"./EventPropagators":25,"./FallbackCompositionState":26,"./SyntheticCompositionEvent":97,"./SyntheticInputEvent":101,"fbjs/lib/ExecutionEnvironment":137,"fbjs/lib/keyOf":155}],10:[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 = { animationIterationCount: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, stopOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; },{}],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 CSSPropertyOperations * @typechecks static-only */ 'use strict'; var CSSProperty = require('./CSSProperty'); var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); var ReactPerf = require('./ReactPerf'); var camelizeStyleName = require('fbjs/lib/camelizeStyleName'); var dangerousStyleValue = require('./dangerousStyleValue'); var hyphenateStyleName = require('fbjs/lib/hyphenateStyleName'); var memoizeStringOnly = require('fbjs/lib/memoizeStringOnly'); var warning = require('fbjs/lib/warning'); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if (process.env.NODE_ENV !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnHyphenatedStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined; }; var warnBadVendoredStyleName = function (name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined; }; var warnStyleValueWithSemicolon = function (name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined; }; /** * @param {string} name * @param {*} value */ var warnValidStyle = function (name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @return {?string} */ createMarkupForStyles: function (styles) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styleValue); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles */ setValueForStyles: function (node, styles) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styles[styleName]); } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', { setValueForStyles: 'setValueForStyles' }); module.exports = CSSPropertyOperations; }).call(this,require('_process')) },{"./CSSProperty":10,"./ReactPerf":78,"./dangerousStyleValue":112,"_process":164,"fbjs/lib/ExecutionEnvironment":137,"fbjs/lib/camelizeStyleName":139,"fbjs/lib/hyphenateStyleName":150,"fbjs/lib/memoizeStringOnly":157,"fbjs/lib/warning":162}],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 CallbackQueue */ 'use strict'; var PooledClass = require('./PooledClass'); var assign = require('./Object.assign'); var invariant = require('fbjs/lib/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) { !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function () { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function () { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; }).call(this,require('_process')) },{"./Object.assign":29,"./PooledClass":30,"_process":164,"fbjs/lib/invariant":151}],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 ChangeEventPlugin */ 'use strict'; var EventConstants = require('./EventConstants'); var EventPluginHub = require('./EventPluginHub'); var EventPropagators = require('./EventPropagators'); var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); var ReactUpdates = require('./ReactUpdates'); var SyntheticEvent = require('./SyntheticEvent'); var getEventTarget = require('./getEventTarget'); var isEventSupported = require('./isEventSupported'); var isTextInputElement = require('./isTextInputElement'); var keyOf = require('fbjs/lib/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) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetID) { activeElement = target; activeElementID = targetID; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementID = null; } function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topChange) { return topLevelTargetID; } } function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9); } /** * (For old IE.) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For old IE.) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetID) { activeElement = target; activeElementID = targetID; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); activeElement.attachEvent('onpropertychange', handlePropertyChange); } /** * (For old IE.) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; activeElement.detachEvent('onpropertychange', handlePropertyChange); activeElement = null; activeElementID = null; activeElementValue = null; activeElementValueProp = null; } /** * (For old IE.) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return topLevelTargetID; } } // For IE8 and IE9. function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(topLevelTarget, topLevelTargetID); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementID; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) { if (topLevelType === topLevelTypes.topClick) { return topLevelTargetID; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var getTargetIDFunc, handleEventFunc; if (shouldUseChangeEvent(topLevelTarget)) { if (doesChangeEventBubble) { getTargetIDFunc = getTargetIDForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(topLevelTarget)) { if (isInputEventSupported) { getTargetIDFunc = getTargetIDForInputEvent; } else { getTargetIDFunc = getTargetIDForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(topLevelTarget)) { getTargetIDFunc = getTargetIDForClickEvent; } if (getTargetIDFunc) { var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID); if (targetID) { var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID); } } }; module.exports = ChangeEventPlugin; },{"./EventConstants":21,"./EventPluginHub":22,"./EventPropagators":25,"./ReactUpdates":90,"./SyntheticEvent":99,"./getEventTarget":121,"./isEventSupported":126,"./isTextInputElement":127,"fbjs/lib/ExecutionEnvironment":137,"fbjs/lib/keyOf":155}],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 ClientReactRootIndex * @typechecks */ 'use strict'; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function () { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],15:[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 ReactPerf = require('./ReactPerf'); var setInnerHTML = require('./setInnerHTML'); var setTextContent = require('./setTextContent'); var invariant = require('fbjs/lib/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`. // fix render order error in safari // IE8 will throw error when index out of list size. var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index); parentNode.insertBefore(childNode, beforeChild); } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: setTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markupList List of markup strings. * @internal */ processUpdates: function (updates, markupList) { var update; // Mapping from parent IDs to initial child orderings. var initialChildren = null; // List of children that will be moved or removed. var updatedChildren = null; for (var i = 0; i < updates.length; i++) { update = updates[i]; if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { var updatedIndex = update.fromIndex; var updatedChild = update.parentNode.childNodes[updatedIndex]; var parentID = update.parentID; !updatedChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined; initialChildren = initialChildren || {}; initialChildren[parentID] = initialChildren[parentID] || []; initialChildren[parentID][updatedIndex] = updatedChild; updatedChildren = updatedChildren || []; updatedChildren.push(updatedChild); } } var renderedMarkup; // markupList is either a list of markup or just a list of elements if (markupList.length && typeof markupList[0] === 'string') { renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); } else { renderedMarkup = markupList; } // Remove updated children first so that `toIndex` is consistent. if (updatedChildren) { for (var j = 0; j < updatedChildren.length; j++) { updatedChildren[j].parentNode.removeChild(updatedChildren[j]); } } for (var k = 0; k < updates.length; k++) { update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex); break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(update.parentNode, update.content); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(update.parentNode, update.content); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above. break; } } } }; ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', { updateTextContent: 'updateTextContent' }); module.exports = DOMChildrenOperations; }).call(this,require('_process')) },{"./Danger":18,"./ReactMultiChildUpdateTypes":74,"./ReactPerf":78,"./setInnerHTML":131,"./setTextContent":132,"_process":164,"fbjs/lib/invariant":151}],16:[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 */ 'use strict'; var invariant = require('fbjs/lib/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. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * DOMPropertyNames: similar to DOMAttributeNames but for DOM properties. * Property names not specified use the normalized name. * * DOMMutationMethods: Properties that require special mutation methods. If * `value` is undefined, the mutation method should unset the property. * * @param {object} domPropertyConfig the config as described above. */ injectDOMPropertyConfig: function (domPropertyConfig) { var Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {}; var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {}; var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {}; if (domPropertyConfig.isCustomAttribute) { DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute); } for (var propName in Properties) { !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE), mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined; !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; var defaultValueCache = {}; /** * DOMProperty exports lookup objects that can be used like functions: * * > DOMProperty.isValid['id'] * true * > DOMProperty.isValid['foobar'] * undefined * * Although this may be confusing, it performs better in general. * * @see http://jsperf.com/key-exists * @see http://jsperf.com/key-missing */ var DOMProperty = { ID_ATTRIBUTE_NAME: 'data-reactid', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseAttribute: * Whether the property must be accessed and mutated using `*Attribute()`. * (This includes anything that fails `<propName> in <element>`.) * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasSideEffects: * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. If true, we read from * the DOM before updating to ensure that the value is only set if it has * changed. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * Whether the property can be used as a flag as well as with a value. * Removed when strictly equal to false; present without a value when * strictly equal to true; present with a value otherwise. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * @type {Object} */ getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null, /** * All of the isCustomAttribute() functions that have been injected. */ _isCustomAttributeFunctions: [], /** * Checks whether a property name is a custom attribute. * @method */ isCustomAttribute: function (attributeName) { for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) { var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i]; if (isCustomAttributeFn(attributeName)) { return true; } } return false; }, /** * Returns the default property value for a DOM property (i.e., not an * attribute). Most default values are '' or false, but not all. Worse yet, * some (in particular, `type`) vary depending on the type of element. * * TODO: Is it better to grab all the possible properties when creating an * element to avoid having to create the same element twice? */ getDefaultValueForProperty: function (nodeName, prop) { var nodeDefaults = defaultValueCache[nodeName]; var testElement; if (!nodeDefaults) { defaultValueCache[nodeName] = nodeDefaults = {}; } if (!(prop in nodeDefaults)) { testElement = document.createElement(nodeName); nodeDefaults[prop] = testElement[prop]; } return nodeDefaults[prop]; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/invariant":151}],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 DOMPropertyOperations * @typechecks static-only */ 'use strict'; var DOMProperty = require('./DOMProperty'); var ReactPerf = require('./ReactPerf'); var quoteAttributeValueForBrowser = require('./quoteAttributeValueForBrowser'); var warning = require('fbjs/lib/warning'); // Simplified subset var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/; var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } if (process.env.NODE_ENV !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function (name) { if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined; }; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); } else if (propertyInfo.mustUseAttribute) { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } else { var propName = propertyInfo.propertyName; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseAttribute) { node.removeAttribute(propertyInfo.attributeName); } else { var propName = propertyInfo.propertyName; var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName); if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) { node[propName] = defaultValue; } } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } else if (process.env.NODE_ENV !== 'production') { warnUnknownProperty(name); } } }; ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', { setValueForProperty: 'setValueForProperty', setValueForAttribute: 'setValueForAttribute', deleteValueForProperty: 'deleteValueForProperty' }); module.exports = DOMPropertyOperations; }).call(this,require('_process')) },{"./DOMProperty":16,"./ReactPerf":78,"./quoteAttributeValueForBrowser":129,"_process":164,"fbjs/lib/warning":162}],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 Danger * @typechecks static-only */ 'use strict'; var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); var createNodesFromMarkup = require('fbjs/lib/createNodesFromMarkup'); var emptyFunction = require('fbjs/lib/emptyFunction'); var getMarkupWrap = require('fbjs/lib/getMarkupWrap'); var invariant = require('fbjs/lib/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) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined; var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { !markupList[i] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined; nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); !!resultList.hasOwnProperty(resultIndex) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined; resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if (process.env.NODE_ENV !== 'production') { console.error('Danger: Discarding unexpected node:', renderNode); } } } // Although resultList was populated out of order, it should now be a dense // array. !(resultListAssignmentCount === resultList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined; !(resultList.length === markupList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined; return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined; !(oldChild.tagName.toLowerCase() !== 'html') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined; var newChild; if (typeof markup === 'string') { newChild = createNodesFromMarkup(markup, emptyFunction)[0]; } else { newChild = markup; } oldChild.parentNode.replaceChild(newChild, oldChild); } }; module.exports = Danger; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/ExecutionEnvironment":137,"fbjs/lib/createNodesFromMarkup":142,"fbjs/lib/emptyFunction":143,"fbjs/lib/getMarkupWrap":147,"fbjs/lib/invariant":151}],19:[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('fbjs/lib/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 })]; module.exports = DefaultEventPluginOrder; },{"fbjs/lib/keyOf":155}],20:[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('fbjs/lib/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, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (topLevelTarget.window === topLevelTarget) { // `topLevelTarget` is probably a window object. win = topLevelTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = topLevelTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; var fromID = ''; var toID = ''; if (topLevelType === topLevelTypes.topMouseOut) { from = topLevelTarget; fromID = topLevelTargetID; to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement); if (to) { toID = ReactMount.getID(to); } else { to = win; } to = to || win; } else { from = win; to = topLevelTarget; toID = topLevelTargetID; } if (from === to) { // Nothing pertains to our managed components. return null; } var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = from; leave.relatedTarget = to; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = to; enter.relatedTarget = from; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID); extractedEvents[0] = leave; extractedEvents[1] = enter; return extractedEvents; } }; module.exports = EnterLeaveEventPlugin; },{"./EventConstants":21,"./EventPropagators":25,"./ReactMount":72,"./SyntheticMouseEvent":103,"fbjs/lib/keyOf":155}],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 EventConstants */ 'use strict'; var keyMirror = require('fbjs/lib/keyMirror'); var PropagationPhases = keyMirror({ bubbled: null, captured: null }); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topAbort: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topVolumeChange: null, topWaiting: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"fbjs/lib/keyMirror":154}],22:[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 ReactErrorUtils = require('./ReactErrorUtils'); var accumulateInto = require('./accumulateInto'); var forEachAccumulated = require('./forEachAccumulated'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave; process.env.NODE_ENV !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined; } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function (InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if (process.env.NODE_ENV !== 'production') { validateInstanceHandle(); } }, getInstanceHandle: function () { if (process.env.NODE_ENV !== 'production') { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function (id, registrationName, listener) { !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined; var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(id, registrationName, listener); } }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (id, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(id, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function (id) { for (var registrationName in listenerBank) { if (!listenerBank[registrationName][id]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(id, registrationName); } delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; }).call(this,require('_process')) },{"./EventPluginRegistry":23,"./EventPluginUtils":24,"./ReactErrorUtils":63,"./accumulateInto":109,"./forEachAccumulated":117,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],23:[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('fbjs/lib/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); !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined; EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, PluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined; EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (InjectedEventPluginOrder) { !!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined; // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined; namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/invariant":151}],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 EventPluginUtils */ 'use strict'; var EventConstants = require('./EventConstants'); var ReactErrorUtils = require('./ReactErrorUtils'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function (InjectedMount) { injection.Mount = InjectedMount; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined; } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if (process.env.NODE_ENV !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, simulated, listener, domID) { var type = event.type || 'unknown-event'; event.currentTarget = injection.Mount.getNode(domID); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchIDs); } event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined; var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getNode: function (id) { return injection.Mount.getNode(id); }, getID: function (node) { return injection.Mount.getID(node); }, injection: injection }; module.exports = EventPluginUtils; }).call(this,require('_process')) },{"./EventConstants":21,"./ReactErrorUtils":63,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],25:[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 warning = require('fbjs/lib/warning'); 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 (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined; } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(domID, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, domID); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(id, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(id, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchIDs = accumulateInto(event._dispatchIDs, id); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event.dispatchMarker, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) { EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; }).call(this,require('_process')) },{"./EventConstants":21,"./EventPluginHub":22,"./accumulateInto":109,"./forEachAccumulated":117,"_process":164,"fbjs/lib/warning":162}],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 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, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; },{"./Object.assign":29,"./PooledClass":30,"./getTextContentAccessor":124}],27:[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 */ 'use strict'; var DOMProperty = require('./DOMProperty'); var ExecutionEnvironment = require('fbjs/lib/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 AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, challenge: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute; // this works on HTML elements too in all browsers except IE8. Conveniently, // IE8 doesn't support SVG and so we can simply use the attribute in // browsers that support SVG and the property in browsers that don't, // regardless of whether the element is HTML or SVG. className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, coords: null, crossOrigin: null, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, formAction: MUST_USE_ATTRIBUTE, formEncType: MUST_USE_ATTRIBUTE, formMethod: MUST_USE_ATTRIBUTE, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: MUST_USE_ATTRIBUTE, frameBorder: MUST_USE_ATTRIBUTE, headers: null, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, high: null, href: null, hrefLang: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, inputMode: MUST_USE_ATTRIBUTE, integrity: null, is: MUST_USE_ATTRIBUTE, keyParams: MUST_USE_ATTRIBUTE, keyType: MUST_USE_ATTRIBUTE, kind: null, label: null, lang: null, list: MUST_USE_ATTRIBUTE, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, low: null, manifest: MUST_USE_ATTRIBUTE, marginHeight: null, marginWidth: null, max: null, maxLength: MUST_USE_ATTRIBUTE, media: MUST_USE_ATTRIBUTE, mediaGroup: null, method: null, min: null, minLength: MUST_USE_ATTRIBUTE, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, nonce: MUST_USE_ATTRIBUTE, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: null, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, sandbox: null, scope: null, scoped: HAS_BOOLEAN_VALUE, scrolling: null, seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: null, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, sizes: MUST_USE_ATTRIBUTE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, srcDoc: MUST_USE_PROPERTY, srcLang: null, srcSet: MUST_USE_ATTRIBUTE, start: HAS_NUMERIC_VALUE, step: null, style: null, summary: null, tabIndex: null, target: null, title: null, type: null, useMap: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, wrap: null, /** * RDFa Properties */ about: MUST_USE_ATTRIBUTE, datatype: MUST_USE_ATTRIBUTE, inlist: MUST_USE_ATTRIBUTE, prefix: MUST_USE_ATTRIBUTE, // property is also supported for OpenGraph in meta tags. property: MUST_USE_ATTRIBUTE, resource: MUST_USE_ATTRIBUTE, 'typeof': MUST_USE_ATTRIBUTE, vocab: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: MUST_USE_ATTRIBUTE, autoCorrect: MUST_USE_ATTRIBUTE, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: null, // color is for Safari mask-icon link color: null, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: MUST_USE_ATTRIBUTE, itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, itemType: MUST_USE_ATTRIBUTE, // itemID and itemRef are for Microdata support as well but // only specified in the the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: MUST_USE_ATTRIBUTE, itemRef: MUST_USE_ATTRIBUTE, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: null, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: MUST_USE_ATTRIBUTE, // IE-only attribute that controls focus behavior unselectable: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: { autoComplete: 'autocomplete', autoFocus: 'autofocus', autoPlay: 'autoplay', autoSave: 'autosave', // `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter. // http://www.w3.org/TR/html5/forms.html#dom-fs-encoding encType: 'encoding', hrefLang: 'hreflang', radioGroup: 'radiogroup', spellCheck: 'spellcheck', srcDoc: 'srcdoc', srcSet: 'srcset' } }; module.exports = HTMLDOMPropertyConfig; },{"./DOMProperty":16,"fbjs/lib/ExecutionEnvironment":137}],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 LinkedValueUtils * @typechecks static-only */ 'use strict'; var ReactPropTypes = require('./ReactPropTypes'); var ReactPropTypeLocations = require('./ReactPropTypeLocations'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: ReactPropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; }).call(this,require('_process')) },{"./ReactPropTypeLocations":80,"./ReactPropTypes":81,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],29:[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; },{}],30:[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('fbjs/lib/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 fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/invariant":151}],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 React */ 'use strict'; var ReactDOM = require('./ReactDOM'); var ReactDOMServer = require('./ReactDOMServer'); var ReactIsomorphic = require('./ReactIsomorphic'); var assign = require('./Object.assign'); var deprecated = require('./deprecated'); // `version` will be added here by ReactIsomorphic. var React = {}; assign(React, ReactIsomorphic); assign(React, { // ReactDOM findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode), render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render), unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode), // ReactDOMServer renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString), renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup) }); React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM; React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer; module.exports = React; },{"./Object.assign":29,"./ReactDOM":42,"./ReactDOMServer":52,"./ReactIsomorphic":70,"./deprecated":113}],32:[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 ReactBrowserComponentMixin */ 'use strict'; var ReactInstanceMap = require('./ReactInstanceMap'); var findDOMNode = require('./findDOMNode'); var warning = require('fbjs/lib/warning'); var didWarnKey = '_getDOMNodeDidWarn'; var ReactBrowserComponentMixin = { /** * Returns the DOM node rendered by this component. * * @return {DOMElement} The root node of this component. * @final * @protected */ getDOMNode: function () { process.env.NODE_ENV !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined; this.constructor[didWarnKey] = true; return findDOMNode(this); } }; module.exports = ReactBrowserComponentMixin; }).call(this,require('_process')) },{"./ReactInstanceMap":69,"./findDOMNode":115,"_process":164,"fbjs/lib/warning":162}],33:[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 ReactPerf = require('./ReactPerf'); 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 = { topAbort: 'abort', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', { putListener: 'putListener', deleteListener: 'deleteListener' }); module.exports = ReactBrowserEventEmitter; },{"./EventConstants":21,"./EventPluginHub":22,"./EventPluginRegistry":23,"./Object.assign":29,"./ReactEventEmitterMixin":64,"./ReactPerf":78,"./ViewportMetrics":108,"./isEventSupported":126}],34:[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 ReactChildReconciler * @typechecks static-only */ 'use strict'; var ReactReconciler = require('./ReactReconciler'); var instantiateReactComponent = require('./instantiateReactComponent'); var shouldUpdateReactComponent = require('./shouldUpdateReactComponent'); var traverseAllChildren = require('./traverseAllChildren'); var warning = require('fbjs/lib/warning'); function instantiateChild(childInstances, child, name) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child, null); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context) { if (nestedChildNodes == null) { return null; } var childInstances = {}; traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return null; } var name; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { ReactReconciler.unmountComponent(prevChild, name); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement, null); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { ReactReconciler.unmountComponent(prevChildren[name]); } } return nextChildren; }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild); } } } }; module.exports = ReactChildReconciler; }).call(this,require('_process')) },{"./ReactReconciler":83,"./instantiateReactComponent":125,"./shouldUpdateReactComponent":133,"./traverseAllChildren":134,"_process":164,"fbjs/lib/warning":162}],35:[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 ReactChildren */ 'use strict'; var PooledClass = require('./PooledClass'); var ReactElement = require('./ReactElement'); var emptyFunction = require('fbjs/lib/emptyFunction'); var traverseAllChildren = require('./traverseAllChildren'); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/(?!\/)/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '//'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func; var context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result; var keyPrefix = bookKeeping.keyPrefix; var func = bookKeeping.func; var context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild !== child ? escapeUserProvidedKey(mappedChild.key || '') + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; },{"./PooledClass":30,"./ReactElement":59,"./traverseAllChildren":134,"fbjs/lib/emptyFunction":143}],36:[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 ReactElement = require('./ReactElement'); var ReactPropTypeLocations = require('./ReactPropTypeLocations'); var ReactPropTypeLocationNames = require('./ReactPropTypeLocationNames'); var ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue'); var assign = require('./Object.assign'); var emptyObject = require('fbjs/lib/emptyObject'); var invariant = require('fbjs/lib/invariant'); var keyMirror = require('fbjs/lib/keyMirror'); var keyOf = require('fbjs/lib/keyOf'); var warning = require('fbjs/lib/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 = []; var warnedSetProps = false; function warnSetProps() { if (!warnedSetProps) { warnedSetProps = true; process.env.NODE_ENV !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined; } } /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); } Constructor.contextTypes = assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); } Constructor.propTypes = assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but not in __DEV__ process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined; } } } function validateMethodOverride(proto, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined; } // Disallow defining methods more than once unless explicitly allowed. if (proto.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classses. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } !(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; !!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined; var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isAlreadyDefined = proto.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { if (!proto.__reactAutoBindMap) { proto.__reactAutoBindMap = {}; } proto.__reactAutoBindMap[name] = property; proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = (name in RESERVED_SPEC_KEYS); !!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined; var isInherited = (name in Constructor); !!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; /* eslint-disable block-scoped-var, no-undef */ boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined; } else if (!args.length) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; /* eslint-enable */ }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { for (var autoBindKey in component.__reactAutoBindMap) { if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) { var method = component.__reactAutoBindMap[autoBindKey]; component[autoBindKey] = bindAutoBindMethod(component, method); } } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); }, /** * Sets a subset of the props. * * @param {object} partialProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ setProps: function (partialProps, callback) { if (process.env.NODE_ENV !== 'production') { warnSetProps(); } this.updater.enqueueSetProps(this, partialProps); if (callback) { this.updater.enqueueCallback(this, callback); } }, /** * Replace all the props. * * @param {object} newProps Subset of the next props. * @param {?function} callback Called after props are updated. * @final * @public * @deprecated */ replaceProps: function (newProps, callback) { if (process.env.NODE_ENV !== 'production') { warnSetProps(); } this.updater.enqueueReplaceProps(this, newProps); if (callback) { this.updater.enqueueCallback(this, callback); } } }; var ReactClassComponent = function () {}; assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { var Constructor = function (props, context, updater) { // This constructor is overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined; } // Wire up auto-binding if (this.__reactAutoBindMap) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined; this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; }).call(this,require('_process')) },{"./Object.assign":29,"./ReactComponent":37,"./ReactElement":59,"./ReactNoopUpdateQueue":76,"./ReactPropTypeLocationNames":79,"./ReactPropTypeLocations":80,"_process":164,"fbjs/lib/emptyObject":144,"fbjs/lib/invariant":151,"fbjs/lib/keyMirror":154,"fbjs/lib/keyOf":155,"fbjs/lib/warning":162}],37:[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 ReactNoopUpdateQueue = require('./ReactNoopUpdateQueue'); var canDefineProperty = require('./canDefineProperty'); var emptyObject = require('fbjs/lib/emptyObject'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined; } this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { var deprecatedAPIs = { getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'], isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceProps: ['replaceProps', 'Instead, call render again at the top level.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'], setProps: ['setProps', 'Instead, call render again at the top level.'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; }).call(this,require('_process')) },{"./ReactNoopUpdateQueue":76,"./canDefineProperty":111,"_process":164,"fbjs/lib/emptyObject":144,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],38:[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 */ '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":47,"./ReactMount":72}],39:[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('fbjs/lib/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) { !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined; ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/invariant":151}],40:[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 ReactCurrentOwner = require('./ReactCurrentOwner'); var ReactElement = require('./ReactElement'); var ReactInstanceMap = require('./ReactInstanceMap'); var ReactPerf = require('./ReactPerf'); var ReactPropTypeLocations = require('./ReactPropTypeLocations'); var ReactPropTypeLocationNames = require('./ReactPropTypeLocationNames'); var ReactReconciler = require('./ReactReconciler'); var ReactUpdateQueue = require('./ReactUpdateQueue'); var assign = require('./Object.assign'); var emptyObject = require('fbjs/lib/emptyObject'); var invariant = require('fbjs/lib/invariant'); var shouldUpdateReactComponent = require('./shouldUpdateReactComponent'); var warning = require('fbjs/lib/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 ''; } function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; return Component(this.props, this.context, this.updater); }; /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = null; this._instance = null; // See ReactUpdateQueue this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (rootID, transaction, context) { this._context = context; this._mountOrder = nextMountID++; this._rootNodeID = rootID; var publicProps = this._processProps(this._currentElement.props); var publicContext = this._processContext(context); var Component = this._currentElement.type; // Initialize the public class var inst; var renderedElement; // This is a way to detect if Component is a stateless arrow function // component, which is not newable. It might not be 100% reliable but is // something we can do until we start detecting that Component extends // React.Component. We already assume that typeof Component === 'function'. var canInstantiate = ('prototype' in Component); if (canInstantiate) { if (process.env.NODE_ENV !== 'production') { ReactCurrentOwner.current = this; try { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } finally { ReactCurrentOwner.current = null; } } else { inst = new Component(publicProps, publicContext, ReactUpdateQueue); } } if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) { renderedElement = inst; inst = new StatelessComponent(Component); } if (process.env.NODE_ENV !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined; } else { // We support ES6 inheriting from React.Component, the module pattern, // and stateless components, but not ES6 classes that don't extend process.env.NODE_ENV !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined; } } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = ReactUpdateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if (process.env.NODE_ENV !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', this.getName() || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } this._renderedComponent = this._instantiateReactComponent(renderedElement); var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context)); if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function () { var inst = this._instance; if (inst.componentWillUnmount) { inst.componentWillUnmount(); } ReactReconciler.unmountComponent(this._renderedComponent); this._renderedComponent = null; this._instance = null; // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = null; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var maskedContext = null; var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; var childContext = inst.getChildContext && inst.getChildContext(); if (childContext) { !(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined; } return assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function (newProps) { if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.propTypes) { this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function (propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // top-level render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined; } } } } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context); } if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext); var nextProps; // Distinguish between a props update versus a simple state update if (prevParentElement === nextParentElement) { // Skip checking prop types again -- we don't read inst.props to avoid // warning for DOM component props in this upgrade nextProps = nextParentElement.props; } else { nextProps = this._processProps(nextParentElement.props); // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (inst.componentWillReceiveProps) { inst.componentWillReceiveProps(nextProps, nextContext); } } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined; } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { inst.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; ReactReconciler.unmountComponent(prevComponentInstance); this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context)); this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup); } }, /** * @protected */ _replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) { ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedComponent = inst.render(); if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function () { var renderedComponent; ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } !( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined; var publicComponentInstance = component.getPublicInstance(); if (process.env.NODE_ENV !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (inst instanceof StatelessComponent) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent', _renderValidatedComponent: '_renderValidatedComponent' }); var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; }).call(this,require('_process')) },{"./Object.assign":29,"./ReactComponentEnvironment":39,"./ReactCurrentOwner":41,"./ReactElement":59,"./ReactInstanceMap":69,"./ReactPerf":78,"./ReactPropTypeLocationNames":79,"./ReactPropTypeLocations":80,"./ReactReconciler":83,"./ReactUpdateQueue":89,"./shouldUpdateReactComponent":133,"_process":164,"fbjs/lib/emptyObject":144,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],41:[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. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],42:[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 */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactCurrentOwner = require('./ReactCurrentOwner'); var ReactDOMTextComponent = require('./ReactDOMTextComponent'); var ReactDefaultInjection = require('./ReactDefaultInjection'); var ReactInstanceHandles = require('./ReactInstanceHandles'); var ReactMount = require('./ReactMount'); var ReactPerf = require('./ReactPerf'); var ReactReconciler = require('./ReactReconciler'); var ReactUpdates = require('./ReactUpdates'); var ReactVersion = require('./ReactVersion'); var findDOMNode = require('./findDOMNode'); var renderSubtreeIntoContainer = require('./renderSubtreeIntoContainer'); var warning = require('fbjs/lib/warning'); ReactDefaultInjection.inject(); var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { findDOMNode: findDOMNode, render: render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* eslint-enable camelcase */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ CurrentOwner: ReactCurrentOwner, InstanceHandles: ReactInstanceHandles, Mount: ReactMount, Reconciler: ReactReconciler, TextComponent: ReactDOMTextComponent }); } if (process.env.NODE_ENV !== 'production') { var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools'); } } // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim, // shams Object.create, Object.freeze]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills'); break; } } } } module.exports = React; }).call(this,require('_process')) },{"./ReactCurrentOwner":41,"./ReactDOMTextComponent":53,"./ReactDefaultInjection":56,"./ReactInstanceHandles":68,"./ReactMount":72,"./ReactPerf":78,"./ReactReconciler":83,"./ReactUpdates":90,"./ReactVersion":91,"./findDOMNode":115,"./renderSubtreeIntoContainer":130,"_process":164,"fbjs/lib/ExecutionEnvironment":137,"fbjs/lib/warning":162}],43:[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 mouseListenerNames = { onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }; /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = { getNativeProps: function (inst, props, context) { if (!props.disabled) { return props; } // Copy the props, except the mouse listeners var nativeProps = {}; for (var key in props) { if (props.hasOwnProperty(key) && !mouseListenerNames[key]) { nativeProps[key] = props[key]; } } return nativeProps; } }; module.exports = ReactDOMButton; },{}],44:[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 AutoFocusUtils = require('./AutoFocusUtils'); var CSSPropertyOperations = require('./CSSPropertyOperations'); var DOMProperty = require('./DOMProperty'); var DOMPropertyOperations = require('./DOMPropertyOperations'); var EventConstants = require('./EventConstants'); var ReactBrowserEventEmitter = require('./ReactBrowserEventEmitter'); var ReactComponentBrowserEnvironment = require('./ReactComponentBrowserEnvironment'); var ReactDOMButton = require('./ReactDOMButton'); var ReactDOMInput = require('./ReactDOMInput'); var ReactDOMOption = require('./ReactDOMOption'); var ReactDOMSelect = require('./ReactDOMSelect'); var ReactDOMTextarea = require('./ReactDOMTextarea'); var ReactMount = require('./ReactMount'); var ReactMultiChild = require('./ReactMultiChild'); var ReactPerf = require('./ReactPerf'); var ReactUpdateQueue = require('./ReactUpdateQueue'); var assign = require('./Object.assign'); var canDefineProperty = require('./canDefineProperty'); var escapeTextContentForBrowser = require('./escapeTextContentForBrowser'); var invariant = require('fbjs/lib/invariant'); var isEventSupported = require('./isEventSupported'); var keyOf = require('fbjs/lib/keyOf'); var setInnerHTML = require('./setInnerHTML'); var setTextContent = require('./setTextContent'); var shallowEqual = require('fbjs/lib/shallowEqual'); var validateDOMNesting = require('./validateDOMNesting'); var warning = require('fbjs/lib/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 CHILDREN = keyOf({ children: null }); var STYLE = keyOf({ style: null }); var HTML = keyOf({ __html: null }); var ELEMENT_NODE_TYPE = 1; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } var legacyPropsDescriptor; if (process.env.NODE_ENV !== 'production') { legacyPropsDescriptor = { props: { enumerable: false, get: function () { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined; return component._currentElement.props; } } }; } function legacyGetDOMNode() { if (process.env.NODE_ENV !== 'production') { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined; } return this; } function legacyIsMounted() { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined; } return !!component; } function legacySetStateEtc() { if (process.env.NODE_ENV !== 'production') { var component = this._reactInternalComponent; process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined; } } function legacySetProps(partialProps, callback) { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; } if (!component) { return; } ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(component, callback); } } function legacyReplaceProps(partialProps, callback) { var component = this._reactInternalComponent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined; } if (!component) { return; } ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(component, callback); } } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined becauses undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (process.env.NODE_ENV !== 'production') { if (voidElementTags[component._tag]) { process.env.NODE_ENV !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined; } } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined; process.env.NODE_ENV !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined; } !(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined; } function enqueuePutListener(id, registrationName, listener, transaction) { if (process.env.NODE_ENV !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined; } var container = ReactMount.findReactContainerForID(id); if (container) { var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container; listenTo(registrationName, doc); } transaction.getReactMountReady().enqueue(putListener, { id: id, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener); } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { topAbort: 'abort', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topSeeked: 'seeked', topSeeking: 'seeking', topStalled: 'stalled', topSuspend: 'suspend', topTimeUpdate: 'timeupdate', topVolumeChange: 'volumechange', topWaiting: 'waiting' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined; var node = ReactMount.getNode(inst._rootNodeID); !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined; switch (inst._tag) { case 'iframe': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); } } break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; break; } } function mountReadyInputWrapper() { ReactDOMInput.mountReadyWrapper(this); } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special cased tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; // NOTE: menuitem's close tag should be omitted, but that causes problems. var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = ({}).hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined; validatedTagCache[tag] = true; } } function processChildContextDev(context, inst) { // Pass down our tag name to child components for validation purposes context = assign({}, context); var info = context[validateDOMNesting.ancestorInfoContextKey]; context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst); return context; } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(tag) { validateDangerousTag(tag); this._tag = tag.toLowerCase(); this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._rootNodeID = null; this._wrapperState = null; this._topLevelWrapper = null; this._nodeWithLegacyProperties = null; if (process.env.NODE_ENV !== 'production') { this._unprocessedContextDev = null; this._processedContextDev = null; } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { construct: function (element) { this._currentElement = element; }, /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {string} rootID The root DOM ID for this node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context * @return {string} The computed markup. */ mountComponent: function (rootID, transaction, context) { this._rootNodeID = rootID; var props = this._currentElement.props; switch (this._tag) { case 'iframe': case 'img': case 'form': case 'video': case 'audio': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'button': props = ReactDOMButton.getNativeProps(this, props, context); break; case 'input': ReactDOMInput.mountWrapper(this, props, context); props = ReactDOMInput.getNativeProps(this, props, context); break; case 'option': ReactDOMOption.mountWrapper(this, props, context); props = ReactDOMOption.getNativeProps(this, props, context); break; case 'select': ReactDOMSelect.mountWrapper(this, props, context); props = ReactDOMSelect.getNativeProps(this, props, context); context = ReactDOMSelect.processChildContext(this, props, context); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, context); props = ReactDOMTextarea.getNativeProps(this, props, context); break; } assertValidProps(this, props); if (process.env.NODE_ENV !== 'production') { if (context[validateDOMNesting.ancestorInfoContextKey]) { validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]); } } if (process.env.NODE_ENV !== 'production') { this._unprocessedContextDev = context; this._processedContextDev = processChildContextDev(context, this); context = this._processedContextDev; } var mountImage; if (transaction.useCreateElement) { var ownerDocument = context[ReactMount.ownerDocumentContextKey]; var el = ownerDocument.createElement(this._currentElement.type); DOMPropertyOperations.setAttributeForID(el, this._rootNodeID); // Populate node cache ReactMount.getID(el); this._updateDOMProperties({}, props, transaction, el); this._createInitialChildren(transaction, props, context, el); mountImage = el; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'input': transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this); // falls through case 'button': case 'select': case 'textarea': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this._rootNodeID, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (process.env.NODE_ENV !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (propKey !== CHILDREN) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID); return ret + ' ' + markupForID; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, el) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { setInnerHTML(el, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node setTextContent(el, contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { el.appendChild(mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'button': lastProps = ReactDOMButton.getNativeProps(this, lastProps); nextProps = ReactDOMButton.getNativeProps(this, nextProps); break; case 'input': ReactDOMInput.updateWrapper(this); lastProps = ReactDOMInput.getNativeProps(this, lastProps); nextProps = ReactDOMInput.getNativeProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getNativeProps(this, lastProps); nextProps = ReactDOMOption.getNativeProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getNativeProps(this, lastProps); nextProps = ReactDOMSelect.getNativeProps(this, nextProps); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); break; } if (process.env.NODE_ENV !== 'production') { // If the context is reference-equal to the old one, pass down the same // processed object so the update bailout in ReactReconciler behaves // correctly (and identically in dev and prod). See #5005. if (this._unprocessedContextDev !== context) { this._unprocessedContextDev = context; this._processedContextDev = processChildContextDev(context, this); } context = this._processedContextDev; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction, null); this._updateDOMChildren(lastProps, nextProps, transaction, context); if (!canDefineProperty && this._nodeWithLegacyProperties) { this._nodeWithLegacyProperties.props = nextProps; } if (this._tag === 'select') { // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction, node) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this._rootNodeID, propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } DOMPropertyOperations.deleteValueForProperty(node, propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey]; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) { continue; } if (propKey === STYLE) { if (nextProp) { if (process.env.NODE_ENV !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this._rootNodeID, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } if (propKey === CHILDREN) { nextProp = null; } DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp); } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { if (!node) { node = ReactMount.getNode(this._rootNodeID); } CSSPropertyOperations.setValueForStyles(node, styleUpdates); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction, context); } }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function () { switch (this._tag) { case 'iframe': case 'img': case 'form': case 'video': case 'audio': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'input': ReactDOMInput.unmountWrapper(this); break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined; break; } this.unmountChildren(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._wrapperState = null; if (this._nodeWithLegacyProperties) { var node = this._nodeWithLegacyProperties; node._reactInternalComponent = null; this._nodeWithLegacyProperties = null; } }, getPublicInstance: function () { if (!this._nodeWithLegacyProperties) { var node = ReactMount.getNode(this._rootNodeID); node._reactInternalComponent = this; node.getDOMNode = legacyGetDOMNode; node.isMounted = legacyIsMounted; node.setState = legacySetStateEtc; node.replaceState = legacySetStateEtc; node.forceUpdate = legacySetStateEtc; node.setProps = legacySetProps; node.replaceProps = legacyReplaceProps; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperties(node, legacyPropsDescriptor); } else { // updateComponent will update this property on subsequent renders node.props = this._currentElement.props; } } else { // updateComponent will update this property on subsequent renders node.props = this._currentElement.props; } this._nodeWithLegacyProperties = node; } return this._nodeWithLegacyProperties; } }; ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent' }); assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; }).call(this,require('_process')) },{"./AutoFocusUtils":8,"./CSSPropertyOperations":11,"./DOMProperty":16,"./DOMPropertyOperations":17,"./EventConstants":21,"./Object.assign":29,"./ReactBrowserEventEmitter":33,"./ReactComponentBrowserEnvironment":38,"./ReactDOMButton":43,"./ReactDOMInput":48,"./ReactDOMOption":49,"./ReactDOMSelect":50,"./ReactDOMTextarea":54,"./ReactMount":72,"./ReactMultiChild":73,"./ReactPerf":78,"./ReactUpdateQueue":89,"./canDefineProperty":111,"./escapeTextContentForBrowser":114,"./isEventSupported":126,"./setInnerHTML":131,"./setTextContent":132,"./validateDOMNesting":135,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/keyOf":155,"fbjs/lib/shallowEqual":160,"fbjs/lib/warning":162}],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 ReactDOMFactories * @typechecks static-only */ 'use strict'; var ReactElement = require('./ReactElement'); var ReactElementValidator = require('./ReactElementValidator'); var mapObject = require('fbjs/lib/mapObject'); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if (process.env.NODE_ENV !== 'production') { return ReactElementValidator.createFactory(tag); } return ReactElement.createFactory(tag); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = mapObject({ a: 'a', abbr: 'abbr', address: 'address', area: 'area', article: 'article', aside: 'aside', audio: 'audio', b: 'b', base: 'base', bdi: 'bdi', bdo: 'bdo', big: 'big', blockquote: 'blockquote', body: 'body', br: 'br', button: 'button', canvas: 'canvas', caption: 'caption', cite: 'cite', code: 'code', col: 'col', colgroup: 'colgroup', data: 'data', datalist: 'datalist', dd: 'dd', del: 'del', details: 'details', dfn: 'dfn', dialog: 'dialog', div: 'div', dl: 'dl', dt: 'dt', em: 'em', embed: 'embed', fieldset: 'fieldset', figcaption: 'figcaption', figure: 'figure', footer: 'footer', form: 'form', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', head: 'head', header: 'header', hgroup: 'hgroup', hr: 'hr', html: 'html', i: 'i', iframe: 'iframe', img: 'img', input: 'input', ins: 'ins', kbd: 'kbd', keygen: 'keygen', label: 'label', legend: 'legend', li: 'li', link: 'link', main: 'main', map: 'map', mark: 'mark', menu: 'menu', menuitem: 'menuitem', meta: 'meta', meter: 'meter', nav: 'nav', noscript: 'noscript', object: 'object', ol: 'ol', optgroup: 'optgroup', option: 'option', output: 'output', p: 'p', param: 'param', picture: 'picture', pre: 'pre', progress: 'progress', q: 'q', rp: 'rp', rt: 'rt', ruby: 'ruby', s: 's', samp: 'samp', script: 'script', section: 'section', select: 'select', small: 'small', source: 'source', span: 'span', strong: 'strong', style: 'style', sub: 'sub', summary: 'summary', sup: 'sup', table: 'table', tbody: 'tbody', td: 'td', textarea: 'textarea', tfoot: 'tfoot', th: 'th', thead: 'thead', time: 'time', title: 'title', tr: 'tr', track: 'track', u: 'u', ul: 'ul', 'var': 'var', video: 'video', wbr: 'wbr', // SVG circle: 'circle', clipPath: 'clipPath', defs: 'defs', ellipse: 'ellipse', g: 'g', image: 'image', line: 'line', linearGradient: 'linearGradient', mask: 'mask', path: 'path', pattern: 'pattern', polygon: 'polygon', polyline: 'polyline', radialGradient: 'radialGradient', rect: 'rect', stop: 'stop', svg: 'svg', text: 'text', tspan: 'tspan' }, createDOMFactory); module.exports = ReactDOMFactories; }).call(this,require('_process')) },{"./ReactElement":59,"./ReactElementValidator":60,"_process":164,"fbjs/lib/mapObject":156}],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 ReactDOMFeatureFlags */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: false }; module.exports = ReactDOMFeatureFlags; },{}],47:[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 */ 'use strict'; var DOMChildrenOperations = require('./DOMChildrenOperations'); var DOMPropertyOperations = require('./DOMPropertyOperations'); var ReactMount = require('./ReactMount'); var ReactPerf = require('./ReactPerf'); var invariant = require('fbjs/lib/invariant'); /** * Errors for properties that should not be updated with `updatePropertyByID()`. * * @type {object} * @private */ var INVALID_PROPERTY_ERRORS = { dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.', style: '`style` must be set using `updateStylesByID()`.' }; /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a DOM node with new property values. This should only be used to * update DOM properties in `DOMProperty`. * * @param {string} id ID of the node to update. * @param {string} name A valid property name, see `DOMProperty`. * @param {*} value New value of the property. * @internal */ updatePropertyByID: function (id, name, value) { var node = ReactMount.getNode(id); !!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined; // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertantly setting to a string. This // brings us in line with the same behavior we have on initial render. if (value != null) { DOMPropertyOperations.setValueForProperty(node, name, value); } else { DOMPropertyOperations.deleteValueForProperty(node, name); } }, /** * Replaces a DOM node that exists in the document with markup. * * @param {string} id ID of child to be replaced. * @param {string} markup Dangerous markup to inject in place of child. * @internal * @see {Danger.dangerouslyReplaceNodeWithMarkup} */ dangerouslyReplaceNodeWithMarkupByID: function (id, markup) { var node = ReactMount.getNode(id); DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup); }, /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @param {array<string>} markup List of markup strings. * @internal */ dangerouslyProcessChildrenUpdates: function (updates, markup) { for (var i = 0; i < updates.length; i++) { updates[i].parentNode = ReactMount.getNode(updates[i].parentID); } DOMChildrenOperations.processUpdates(updates, markup); } }; ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID', dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' }); module.exports = ReactDOMIDOperations; }).call(this,require('_process')) },{"./DOMChildrenOperations":15,"./DOMPropertyOperations":17,"./ReactMount":72,"./ReactPerf":78,"_process":164,"fbjs/lib/invariant":151}],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 ReactDOMIDOperations = require('./ReactDOMIDOperations'); var LinkedValueUtils = require('./LinkedValueUtils'); var ReactMount = require('./ReactMount'); var ReactUpdates = require('./ReactUpdates'); var assign = require('./Object.assign'); var invariant = require('fbjs/lib/invariant'); var instancesByReactID = {}; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getNativeProps: function (inst, props, context) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var nativeProps = assign({}, props, { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null, onChange: _handleChange.bind(inst) }; }, mountReadyWrapper: function (inst) { // Can't be in mountWrapper or else server rendering leaks. instancesByReactID[inst._rootNodeID] = inst; }, unmountWrapper: function (inst) { delete instancesByReactID[inst._rootNodeID]; }, updateWrapper: function (inst) { var props = inst._currentElement.props; // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false); } var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactMount.getNode(this._rootNodeID); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React with non-React. var otherID = ReactMount.getID(otherNode); !otherID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined; var otherInstance = instancesByReactID[otherID]; !otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; }).call(this,require('_process')) },{"./LinkedValueUtils":28,"./Object.assign":29,"./ReactDOMIDOperations":47,"./ReactMount":72,"./ReactUpdates":90,"_process":164,"fbjs/lib/invariant":151}],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 ReactChildren = require('./ReactChildren'); var ReactDOMSelect = require('./ReactDOMSelect'); var assign = require('./Object.assign'); var warning = require('fbjs/lib/warning'); var valueContextKey = ReactDOMSelect.valueContextKey; /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, context) { // TODO (yungsters): Remove support for `selected` in <option>. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined; } // Look up whether this option is 'selected' via context var selectValue = context[valueContextKey]; // If context key is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === '' + props.value) { selected = true; break; } } } else { selected = '' + selectValue === '' + props.value; } } inst._wrapperState = { selected: selected }; }, getNativeProps: function (inst, props, context) { var nativeProps = assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { nativeProps.selected = inst._wrapperState.selected; } var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined; } }); nativeProps.children = content; return nativeProps; } }; module.exports = ReactDOMOption; }).call(this,require('_process')) },{"./Object.assign":29,"./ReactChildren":35,"./ReactDOMSelect":50,"_process":164,"fbjs/lib/warning":162}],50:[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 ReactDOMSelect */ 'use strict'; var LinkedValueUtils = require('./LinkedValueUtils'); var ReactMount = require('./ReactMount'); var ReactUpdates = require('./ReactUpdates'); var assign = require('./Object.assign'); var warning = require('fbjs/lib/warning'); var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2); function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } if (props.multiple) { process.env.NODE_ENV !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactMount.getNode(inst._rootNodeID).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { valueContextKey: valueContextKey, getNativeProps: function (inst, props, context) { return assign({}, props, { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { checkSelectPropTypes(inst, props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; }, processChildContext: function (inst, props, context) { // Pass down initial value so initial generated markup has correct // `selected` attributes var childContext = assign({}, context); childContext[valueContextKey] = inst._wrapperState.initialValue; return childContext; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; // After the initial mount, we control selected-ness manually so don't pass // the context value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); this._wrapperState.pendingUpdate = true; ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; }).call(this,require('_process')) },{"./LinkedValueUtils":28,"./Object.assign":29,"./ReactMount":72,"./ReactUpdates":90,"_process":164,"fbjs/lib/warning":162}],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('fbjs/lib/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); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (typeof offsets.end === 'undefined') { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; },{"./getNodeForCharacterOffset":123,"./getTextContentAccessor":124,"fbjs/lib/ExecutionEnvironment":137}],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 ReactDOMServer */ 'use strict'; var ReactDefaultInjection = require('./ReactDefaultInjection'); var ReactServerRendering = require('./ReactServerRendering'); var ReactVersion = require('./ReactVersion'); ReactDefaultInjection.inject(); var ReactDOMServer = { renderToString: ReactServerRendering.renderToString, renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup, version: ReactVersion }; module.exports = ReactDOMServer; },{"./ReactDefaultInjection":56,"./ReactServerRendering":87,"./ReactVersion":91}],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 ReactDOMTextComponent * @typechecks static-only */ 'use strict'; var DOMChildrenOperations = require('./DOMChildrenOperations'); var DOMPropertyOperations = require('./DOMPropertyOperations'); var ReactComponentBrowserEnvironment = require('./ReactComponentBrowserEnvironment'); var ReactMount = require('./ReactMount'); var assign = require('./Object.assign'); var escapeTextContentForBrowser = require('./escapeTextContentForBrowser'); var setTextContent = require('./setTextContent'); var validateDOMNesting = require('./validateDOMNesting'); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings in elements so that they can undergo * the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (props) { // This constructor and its argument is currently used by mocks. }; assign(ReactDOMTextComponent.prototype, { /** * @param {ReactText} text * @internal */ construct: function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // Properties this._rootNodeID = null; this._mountIndex = 0; }, /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (rootID, transaction, context) { if (process.env.NODE_ENV !== 'production') { if (context[validateDOMNesting.ancestorInfoContextKey]) { validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]); } } this._rootNodeID = rootID; if (transaction.useCreateElement) { var ownerDocument = context[ReactMount.ownerDocumentContextKey]; var el = ownerDocument.createElement('span'); DOMPropertyOperations.setAttributeForID(el, rootID); // Populate node cache ReactMount.getID(el); setTextContent(el, this._stringText); return el; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this in a `span` for the reasons stated above, but // since this is a situation where React won't take over (static pages), // we can simply return the text as it is. return escapedText; } return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var node = ReactMount.getNode(this._rootNodeID); DOMChildrenOperations.updateTextContent(node, nextStringText); } } }, unmountComponent: function () { ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); } }); module.exports = ReactDOMTextComponent; }).call(this,require('_process')) },{"./DOMChildrenOperations":15,"./DOMPropertyOperations":17,"./Object.assign":29,"./ReactComponentBrowserEnvironment":38,"./ReactMount":72,"./escapeTextContentForBrowser":114,"./setTextContent":132,"./validateDOMNesting":135,"_process":164}],54:[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 LinkedValueUtils = require('./LinkedValueUtils'); var ReactDOMIDOperations = require('./ReactDOMIDOperations'); var ReactUpdates = require('./ReactUpdates'); var assign = require('./Object.assign'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getNativeProps: function (inst, props, context) { !(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. var nativeProps = assign({}, props, { defaultValue: undefined, value: undefined, children: inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); } var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined; } !(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined; if (Array.isArray(children)) { !(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue), onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; }).call(this,require('_process')) },{"./LinkedValueUtils":28,"./Object.assign":29,"./ReactDOMIDOperations":47,"./ReactUpdates":90,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],55:[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('fbjs/lib/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, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; },{"./Object.assign":29,"./ReactUpdates":90,"./Transaction":107,"fbjs/lib/emptyFunction":143}],56:[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('fbjs/lib/ExecutionEnvironment'); var HTMLDOMPropertyConfig = require('./HTMLDOMPropertyConfig'); var ReactBrowserComponentMixin = require('./ReactBrowserComponentMixin'); var ReactComponentBrowserEnvironment = require('./ReactComponentBrowserEnvironment'); var ReactDefaultBatchingStrategy = require('./ReactDefaultBatchingStrategy'); var ReactDOMComponent = require('./ReactDOMComponent'); var ReactDOMTextComponent = require('./ReactDOMTextComponent'); 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 alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles); ReactInjection.EventPluginHub.injectMount(ReactMount); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.Class.injectMixin(ReactBrowserComponentMixin); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponent('noscript'); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); if (process.env.NODE_ENV !== 'production') { var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { var ReactDefaultPerf = require('./ReactDefaultPerf'); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; }).call(this,require('_process')) },{"./BeforeInputEventPlugin":9,"./ChangeEventPlugin":13,"./ClientReactRootIndex":14,"./DefaultEventPluginOrder":19,"./EnterLeaveEventPlugin":20,"./HTMLDOMPropertyConfig":27,"./ReactBrowserComponentMixin":32,"./ReactComponentBrowserEnvironment":38,"./ReactDOMComponent":44,"./ReactDOMTextComponent":53,"./ReactDefaultBatchingStrategy":55,"./ReactDefaultPerf":57,"./ReactEventListener":65,"./ReactInjection":66,"./ReactInstanceHandles":68,"./ReactMount":72,"./ReactReconcileTransaction":82,"./SVGDOMPropertyConfig":92,"./SelectEventPlugin":93,"./ServerReactRootIndex":94,"./SimpleEventPlugin":95,"_process":164,"fbjs/lib/ExecutionEnvironment":137}],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 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('fbjs/lib/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 _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var totalTime; var rv; var start; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push({ exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, totalTime: 0, created: {} }); start = performanceNow(); rv = func.apply(this, args); ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { var mountID = ReactMount.getID(args[1]); ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[0].forEach(function (update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.textContent !== null) { writeArgs.textContent = update.textContent; } if (update.markupIndex !== null) { writeArgs.markup = args[1][update.markupIndex]; } ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs); }); } else { // basic format var id = args[0]; if (typeof id === 'object') { id = ReactMount.getID(args[0]); } ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); } return rv; } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { if (this._currentElement.type === ReactMount.TopLevelWrapper) { return func.apply(this, args); } var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID; var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { entry.created[rootNodeID] = true; mountStack.push(0); } start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; },{"./DOMProperty":16,"./ReactDefaultPerfAnalysis":58,"./ReactMount":72,"./ReactPerf":78,"fbjs/lib/performanceNow":159}],58:[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 */ 'use strict'; 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', SET_MARKUP: 'set innerHTML', TEXT_CONTENT: 'set textContent', 'setValueForProperty': 'update attribute', 'setValueForAttribute': 'update attribute', 'deleteValueForProperty': 'remove attribute', 'setValueForStyles': 'update styles', 'replaceNodeWithMarkup': 'replace', 'updateTextContent': 'set textContent' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; measurements.forEach(function (measurement) { Object.keys(measurement.writes).forEach(function (id) { measurement.writes[id].forEach(function (write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); }); }); return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function (a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = assign({}, measurement.exclusive, measurement.inclusive); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function (a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var dirtyLeafIDs = Object.keys(measurement.writes); var allIDs = assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // For each component that rendered, see if a component that triggered // a DOM op is in its subtree. for (var i = 0; i < dirtyLeafIDs.length; i++) { if (dirtyLeafIDs[i].indexOf(id) === 0) { isDirty = true; break; } } // check if component newly created if (measurement.created[id]) { isDirty = true; } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; },{"./Object.assign":29}],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 ReactElement */ 'use strict'; var ReactCurrentOwner = require('./ReactCurrentOwner'); var assign = require('./Object.assign'); var canDefineProperty = require('./canDefineProperty'); // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; /** * Base constructor for all React elements. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (process.env.NODE_ENV !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } Object.freeze(element.props); Object.freeze(element); } return element; }; ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (typeof props[propName] === 'undefined') { props[propName] = defaultProps[propName]; } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; ReactElement.cloneAndReplaceProps = function (oldElement, newProps) { var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps); if (process.env.NODE_ENV !== 'production') { // If the key on the original is valid, then the clone is valid newElement._store.validated = oldElement._store.validated; } return newElement; }; ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; }).call(this,require('_process')) },{"./Object.assign":29,"./ReactCurrentOwner":41,"./canDefineProperty":111,"_process":164}],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 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 ReactPropTypeLocations = require('./ReactPropTypeLocations'); var ReactPropTypeLocationNames = require('./ReactPropTypeLocationNames'); var ReactCurrentOwner = require('./ReactCurrentOwner'); var canDefineProperty = require('./canDefineProperty'); var getIteratorFn = require('./getIteratorFn'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/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 = {}; /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var addenda = getAddendaForKeyUse('uniqueKey', element, parentType); if (addenda === null) { // we already showed the warning return; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined; } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} messageType A key used for de-duping warnings. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. * @returns {?object} A set of addenda to use in the warning message, or null * if the warning has already been shown before (and shouldn't be shown again). */ function getAddendaForKeyUse(messageType, element, parentType) { var addendum = getDeclarationErrorAddendum(); if (!addendum) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { addendum = ' Check the top-level render call using <' + parentName + '>.'; } } var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {}); if (memoizer[addendum]) { return null; } memoizer[addendum] = true; var addenda = { parentOrOwner: addendum, url: ' See https://fb.me/react-warning-keys for more information.', childOwner: null }; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } return addenda; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined; } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. process.env.NODE_ENV !== 'production' ? warning(validType, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : undefined; var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; }).call(this,require('_process')) },{"./ReactCurrentOwner":41,"./ReactElement":59,"./ReactPropTypeLocationNames":79,"./ReactPropTypeLocations":80,"./canDefineProperty":111,"./getIteratorFn":122,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],61:[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 ReactEmptyComponent */ 'use strict'; var ReactElement = require('./ReactElement'); var ReactEmptyComponentRegistry = require('./ReactEmptyComponentRegistry'); var ReactReconciler = require('./ReactReconciler'); var assign = require('./Object.assign'); var placeholderElement; var ReactEmptyComponentInjection = { injectEmptyComponent: function (component) { placeholderElement = ReactElement.createElement(component); } }; var ReactEmptyComponent = function (instantiate) { this._currentElement = null; this._rootNodeID = null; this._renderedComponent = instantiate(placeholderElement); }; assign(ReactEmptyComponent.prototype, { construct: function (element) {}, mountComponent: function (rootID, transaction, context) { ReactEmptyComponentRegistry.registerNullComponentID(rootID); this._rootNodeID = rootID; return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context); }, receiveComponent: function () {}, unmountComponent: function (rootID, transaction, context) { ReactReconciler.unmountComponent(this._renderedComponent); ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID); this._rootNodeID = null; this._renderedComponent = null; } }); ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; },{"./Object.assign":29,"./ReactElement":59,"./ReactEmptyComponentRegistry":62,"./ReactReconciler":83}],62:[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 ReactEmptyComponentRegistry */ 'use strict'; // This registry keeps track of the React IDs of the components that rendered to // `null` (in reality a placeholder such as `noscript`) var nullComponentIDsRegistry = {}; /** * @param {string} id Component's `_rootNodeID`. * @return {boolean} True if the component is rendered to null. */ function isNullComponentID(id) { return !!nullComponentIDsRegistry[id]; } /** * Mark the component as having rendered to null. * @param {string} id Component's `_rootNodeID`. */ function registerNullComponentID(id) { nullComponentIDsRegistry[id] = true; } /** * Unmark the component as having rendered to null: it renders to something now. * @param {string} id Component's `_rootNodeID`. */ function deregisterNullComponentID(id) { delete nullComponentIDsRegistry[id]; } var ReactEmptyComponentRegistry = { isNullComponentID: isNullComponentID, registerNullComponentID: registerNullComponentID, deregisterNullComponentID: deregisterNullComponentID }; module.exports = ReactEmptyComponentRegistry; },{}],63:[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 ReactErrorUtils * @typechecks */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { if (caughtError === null) { caughtError = x; } return undefined; } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if (process.env.NODE_ENV !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { var boundFunc = func.bind(null, a, b); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; }).call(this,require('_process')) },{"_process":164}],64:[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(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"./EventPluginHub":22}],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 ReactEventListener * @typechecks static-only */ 'use strict'; var EventListener = require('fbjs/lib/EventListener'); var ExecutionEnvironment = require('fbjs/lib/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('fbjs/lib/getUnboundedScrollPosition'); var DOCUMENT_FRAGMENT_NODE_TYPE = 11; /** * Finds the parent React component of `node`. * * @param {*} node * @return {?DOMEventTarget} Parent container, or `null` if the specified node * is not nested. */ function findParent(node) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. var nodeID = ReactMount.getID(node); var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); var container = ReactMount.findReactContainerForID(rootID); var parent = ReactMount.getFirstReactDOM(container); return parent; } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { // TODO: Re-enable event.path handling // // if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) { // // New browsers have a path attribute on native events // handleTopLevelWithPath(bookKeeping); // } else { // // Legacy browsers don't have a path attribute on native events // handleTopLevelWithoutPath(bookKeeping); // } void handleTopLevelWithPath; // temporarily unused handleTopLevelWithoutPath(bookKeeping); } // Legacy browsers don't have a path attribute on native events function handleTopLevelWithoutPath(bookKeeping) { var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window; // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = topLevelTarget; while (ancestor) { bookKeeping.ancestors.push(ancestor); ancestor = findParent(ancestor); } for (var i = 0; i < bookKeeping.ancestors.length; i++) { topLevelTarget = bookKeeping.ancestors[i]; var topLevelTargetID = ReactMount.getID(topLevelTarget) || ''; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } // New browsers have a path attribute on native events function handleTopLevelWithPath(bookKeeping) { var path = bookKeeping.nativeEvent.path; var currentNativeTarget = path[0]; var eventsFired = 0; for (var i = 0; i < path.length; i++) { var currentPathElement = path[i]; if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) { currentNativeTarget = path[i + 1]; } // TODO: slow var reactParent = ReactMount.getFirstReactDOM(currentPathElement); if (reactParent === currentPathElement) { var currentPathElementID = ReactMount.getID(currentPathElement); var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID); bookKeeping.ancestors.push(currentPathElement); var topLevelTargetID = ReactMount.getID(currentPathElement) || ''; eventsFired++; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget); // Jump to the root of this React render tree while (currentPathElementID !== newRootID) { i++; currentPathElement = path[i]; currentPathElementID = ReactMount.getID(currentPathElement); } } } if (eventsFired === 0) { ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; },{"./Object.assign":29,"./PooledClass":30,"./ReactInstanceHandles":68,"./ReactMount":72,"./ReactUpdates":90,"./getEventTarget":121,"fbjs/lib/EventListener":136,"fbjs/lib/ExecutionEnvironment":137,"fbjs/lib/getUnboundedScrollPosition":148}],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 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 ReactPerf = require('./ReactPerf'); var ReactRootIndex = require('./ReactRootIndex'); var ReactUpdates = require('./ReactUpdates'); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, RootIndex: ReactRootIndex.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; },{"./DOMProperty":16,"./EventPluginHub":22,"./ReactBrowserEventEmitter":33,"./ReactClass":36,"./ReactComponentEnvironment":39,"./ReactEmptyComponent":61,"./ReactNativeComponent":75,"./ReactPerf":78,"./ReactRootIndex":85,"./ReactUpdates":90}],67:[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('fbjs/lib/containsNode'); var focusNode = require('fbjs/lib/focusNode'); var getActiveElement = require('fbjs/lib/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) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (typeof end === 'undefined') { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; },{"./ReactDOMSelection":51,"fbjs/lib/containsNode":140,"fbjs/lib/focusNode":145,"fbjs/lib/getActiveElement":146}],68:[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('fbjs/lib/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 = 10000; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR; } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { !(isValidID(ancestorID) && isValidID(destinationID)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined; !isAncestorIDOf(ancestorID, destinationID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined; if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; var i; for (i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); !isValidID(longestCommonID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined; return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {*} arg Argument to invoke the callback with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; !(start !== stop) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined; var traverseUp = isAncestorIDOf(stop, start); !(traverseUp || isAncestorIDOf(start, stop)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined; // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start;; /* until break */id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } !(depth++ < MAX_TREE_DEPTH) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined; } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function () { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function (rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function (id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function (targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Same as `traverseTwoPhase` but skips the `targetID`. */ traverseTwoPhaseSkipTarget: function (targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, true); traverseParentPath(targetID, '', cb, arg, true, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function (targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; }).call(this,require('_process')) },{"./ReactRootIndex":85,"_process":164,"fbjs/lib/invariant":151}],69:[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; },{}],70:[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 ReactIsomorphic */ 'use strict'; var ReactChildren = require('./ReactChildren'); var ReactComponent = require('./ReactComponent'); var ReactClass = require('./ReactClass'); var ReactDOMFactories = require('./ReactDOMFactories'); var ReactElement = require('./ReactElement'); var ReactElementValidator = require('./ReactElementValidator'); var ReactPropTypes = require('./ReactPropTypes'); var ReactVersion = require('./ReactVersion'); var assign = require('./Object.assign'); var onlyChild = require('./onlyChild'); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (process.env.NODE_ENV !== 'production') { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Hook for JSX spread, don't use this for anything else. __spread: assign }; module.exports = React; }).call(this,require('_process')) },{"./Object.assign":29,"./ReactChildren":35,"./ReactClass":36,"./ReactComponent":37,"./ReactDOMFactories":45,"./ReactElement":59,"./ReactElementValidator":60,"./ReactPropTypes":81,"./ReactVersion":91,"./onlyChild":128,"_process":164}],71:[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 TAG_END = /\/?>/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags and self-closing tags) return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"./adler32":110}],72:[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 ReactDOMFeatureFlags = require('./ReactDOMFeatureFlags'); var ReactElement = require('./ReactElement'); var ReactEmptyComponentRegistry = require('./ReactEmptyComponentRegistry'); 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 assign = require('./Object.assign'); var emptyObject = require('fbjs/lib/emptyObject'); var containsNode = require('fbjs/lib/containsNode'); var instantiateReactComponent = require('./instantiateReactComponent'); var invariant = require('fbjs/lib/invariant'); var setInnerHTML = require('./setInnerHTML'); var shouldUpdateReactComponent = require('./shouldUpdateReactComponent'); var validateDOMNesting = require('./validateDOMNesting'); var warning = require('fbjs/lib/warning'); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var nodeCache = {}; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2); /** Mapping from reactRootID to React component instance. */ var instancesByReactRootID = {}; /** Mapping from reactRootID to `container` nodes. */ var containersByReactRootID = {}; if (process.env.NODE_ENV !== 'production') { /** __DEV__-only mapping from reactRootID to root elements. */ var rootElementsByReactRootID = {}; } // Used to store breadth-first search state in findComponentRoot. var findComponentRootReusableArray = []; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } /** * @param {DOMElement} container DOM element that may contain a React component. * @return {?string} A "reactRoot" ID, if a React component is rendered. */ function getReactRootID(container) { var rootElement = getReactRootElementInContainer(container); return rootElement && ReactMount.getID(rootElement); } /** * Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form * element can return its control whose name or ID equals ATTR_NAME. All * DOM nodes support `getAttributeNode` but this can also get called on * other objects so just return '' if we're given something other than a * DOM node (such as window). * * @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node. * @return {string} ID of the supplied `domNode`. */ function getID(node) { var id = internalGetID(node); if (id) { if (nodeCache.hasOwnProperty(id)) { var cached = nodeCache[id]; if (cached !== node) { !!isValid(cached, id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined; nodeCache[id] = node; } } else { nodeCache[id] = node; } } return id; } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node && node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Sets the React-specific ID of the given node. * * @param {DOMElement} node The DOM node whose ID will be set. * @param {string} id The value of the ID attribute. */ function setID(node, id) { var oldID = internalGetID(node); if (oldID !== id) { delete nodeCache[oldID]; } node.setAttribute(ATTR_NAME, id); nodeCache[id] = node; } /** * Finds the node with the supplied React-generated DOM ID. * * @param {string} id A React-generated DOM ID. * @return {DOMElement} DOM node with the suppled `id`. * @internal */ function getNode(id) { if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * Finds the node with the supplied public React instance. * * @param {*} instance A public React instance. * @return {?DOMElement} DOM node with the suppled `id`. * @internal */ function getNodeFromInstance(instance) { var id = ReactInstanceMap.get(instance)._rootNodeID; if (ReactEmptyComponentRegistry.isNullComponentID(id)) { return null; } if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) { nodeCache[id] = ReactMount.findReactNodeByID(id); } return nodeCache[id]; } /** * A node is "valid" if it is contained by a currently mounted container. * * This means that the node does not have to be contained by a document in * order to be considered valid. * * @param {?DOMElement} node The candidate DOM node. * @param {string} id The expected ID of the node. * @return {boolean} Whether the node is contained by a mounted container. */ function isValid(node, id) { if (node) { !(internalGetID(node) === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined; var container = ReactMount.findReactContainerForID(id); if (container && containsNode(container, node)) { return true; } } return false; } /** * Causes the cache to forget about one React-specific ID. * * @param {string} id The ID to forget. */ function purgeID(id) { delete nodeCache[id]; } var deepestNodeSoFar = null; function findDeepestCachedAncestorImpl(ancestorID) { var ancestor = nodeCache[ancestorID]; if (ancestor && isValid(ancestor, ancestorID)) { deepestNodeSoFar = ancestor; } else { // This node isn't populated in the cache, so presumably none of its // descendants are. Break out of the loop. return false; } } /** * Return the deepest cached node whose ID is a prefix of `targetID`. */ function findDeepestCachedAncestor(targetID) { deepestNodeSoFar = null; ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl); var foundNode = deepestNodeSoFar; deepestNodeSoFar = null; return foundNode; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) { if (ReactDOMFeatureFlags.useCreateElement) { context = assign({}, context); if (container.nodeType === DOC_NODE_TYPE) { context[ownerDocumentContextKey] = container; } else { context[ownerDocumentContextKey] = container.ownerDocument; } } if (process.env.NODE_ENV !== 'production') { if (context === emptyObject) { context = {}; } var tag = container.nodeName.toLowerCase(); context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null); } var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context); componentInstance._renderedComponent._topLevelWrapper = componentInstance; ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {string} rootID DOM ID of the root node. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */shouldReuseMarkup); transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container) { ReactReconciler.unmountComponent(instance); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(node) { var reactRootID = getReactRootID(node); return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false; } /** * Returns the first (deepest) ancestor of a node which is rendered by this copy * of React. */ function findFirstReactDOMImpl(node) { // This node might be from another React instance, so we make sure not to // examine the node cache here for (; node && node.parentNode !== node; node = node.parentNode) { if (node.nodeType !== 1) { // Not a DOMElement, therefore not a React component continue; } var nodeID = internalGetID(node); if (!nodeID) { continue; } var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID); // If containersByReactRootID contains the container we find by crawling up // the tree, we know that this instance of React rendered the node. // nb. isValid's strategy (with containsNode) does not work because render // trees may be nested and we don't want a false positive in that case. var current = node; var lastID; do { lastID = internalGetID(current); current = current.parentNode; if (current == null) { // The passed-in node has been detached from the container it was // originally rendered into. return null; } } while (lastID !== reactRootID); if (current === containersByReactRootID[reactRootID]) { return node; } } return null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var TopLevelWrapper = function () {}; TopLevelWrapper.prototype.isReactComponent = {}; if (process.env.NODE_ENV !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { // this.props is actually a ReactElement return this.props; }; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** Exposed for debugging purposes **/ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); if (process.env.NODE_ENV !== 'production') { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container); } return prevComponent; }, /** * Register a component into the instance map and starts scroll value * monitoring * @param {ReactComponent} nextComponent component instance to render * @param {DOMElement} container container to render into * @return {string} reactRoot ID prefix */ _registerComponent: function (nextComponent, container) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var reactRootID = ReactMount.registerContainer(container); instancesByReactRootID[reactRootID] = nextComponent; return reactRootID; }, /** * Render a new component into the DOM. * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; var componentInstance = instantiateReactComponent(nextElement, null); var reactRootID = ReactMount._registerComponent(componentInstance, container); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context); if (process.env.NODE_ENV !== 'production') { // Record the root element in case it later gets transplanted. rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container); } return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && parentComponent._reactInternalInstance != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined; process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined; var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); var prevComponent = instancesByReactRootID[getReactRootID(container)]; if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined; break; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Registers a container node into which React components will be rendered. * This also creates the "reactRoot" ID that will be assigned to the element * rendered within. * * @param {DOMElement} container DOM element to register as a container. * @return {string} The "reactRoot" ID of elements rendered within. */ registerContainer: function (container) { var reactRootID = getReactRootID(container); if (reactRootID) { // If one exists, make sure it is a valid "reactRoot" ID. reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID); } if (!reactRootID) { // No valid "reactRoot" ID found, create one. reactRootID = ReactInstanceHandles.createReactRootID(); } containersByReactRootID[reactRootID] = container; return reactRootID; }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined; var reactRootID = getReactRootID(container); var component = instancesByReactRootID[reactRootID]; if (!component) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var containerID = internalGetID(container); var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined; } return false; } ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container); delete instancesByReactRootID[reactRootID]; delete containersByReactRootID[reactRootID]; if (process.env.NODE_ENV !== 'production') { delete rootElementsByReactRootID[reactRootID]; } return true; }, /** * Finds the container DOM element that contains React component to which the * supplied DOM `id` belongs. * * @param {string} id The ID of an element rendered by a React component. * @return {?DOMElement} DOM element that contains the `id`. */ findReactContainerForID: function (id) { var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id); var container = containersByReactRootID[reactRootID]; if (process.env.NODE_ENV !== 'production') { var rootElement = rootElementsByReactRootID[reactRootID]; if (rootElement && rootElement.parentNode !== container) { process.env.NODE_ENV !== 'production' ? warning( // Call internalGetID here because getID calls isValid which calls // findReactContainerForID (this function). internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined; var containerChild = container.firstChild; if (containerChild && reactRootID === internalGetID(containerChild)) { // If the container has a new child with the same ID as the old // root element, then rootElementsByReactRootID[reactRootID] is // just stale and needs to be updated. The case that deserves a // warning is when the container is empty. rootElementsByReactRootID[reactRootID] = containerChild; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined; } } } return container; }, /** * Finds an element rendered by React with the supplied ID. * * @param {string} id ID of a DOM node in the React component. * @return {DOMElement} Root DOM node of the React component. */ findReactNodeByID: function (id) { var reactRoot = ReactMount.findReactContainerForID(id); return ReactMount.findComponentRoot(reactRoot, id); }, /** * Traverses up the ancestors of the supplied node to find a node that is a * DOM representation of a React component rendered by this copy of React. * * @param {*} node * @return {?DOMEventTarget} * @internal */ getFirstReactDOM: function (node) { return findFirstReactDOMImpl(node); }, /** * Finds a node with the supplied `targetID` inside of the supplied * `ancestorNode`. Exploits the ID naming scheme to perform the search * quickly. * * @param {DOMEventTarget} ancestorNode Search from this root. * @pararm {string} targetID ID of the DOM representation of the component. * @return {DOMEventTarget} DOM node with the supplied `targetID`. * @internal */ findComponentRoot: function (ancestorNode, targetID) { var firstChildren = findComponentRootReusableArray; var childIndex = 0; var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode; if (process.env.NODE_ENV !== 'production') { // This will throw on the next line; give an early warning process.env.NODE_ENV !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined; } firstChildren[0] = deepestAncestor.firstChild; firstChildren.length = 1; while (childIndex < firstChildren.length) { var child = firstChildren[childIndex++]; var targetChild; while (child) { var childID = ReactMount.getID(child); if (childID) { // Even if we find the node we're looking for, we finish looping // through its siblings to ensure they're cached so that we don't have // to revisit this node again. Otherwise, we make n^2 calls to getID // when visiting the many children of a single node in order. if (targetID === childID) { targetChild = child; } else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) { // If we find a child whose ID is an ancestor of the given ID, // then we can be sure that we only want to search the subtree // rooted at this child, so we can throw out the rest of the // search state. firstChildren.length = childIndex = 0; firstChildren.push(child.firstChild); } } else { // If this child had no ID, then there's a chance that it was // injected automatically by the browser, as when a `<table>` // element sprouts an extra `<tbody>` child as a side effect of // `.innerHTML` parsing. Optimistically continue down this // branch, but not before examining the other siblings. firstChildren.push(child.firstChild); } child = child.nextSibling; } if (targetChild) { // Emptying firstChildren/findComponentRootReusableArray is // not necessary for correctness, but it helps the GC reclaim // any nodes that were left at the end of the search. firstChildren.length = 0; return targetChild; } } firstChildren.length = 0; !false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined; }, _mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if (process.env.NODE_ENV !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined; } } } !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } container.appendChild(markup); } else { setInnerHTML(container, markup); } }, ownerDocumentContextKey: ownerDocumentContextKey, /** * React ID utilities. */ getReactRootID: getReactRootID, getID: getID, setID: setID, getNode: getNode, getNodeFromInstance: getNodeFromInstance, isValid: isValid, purgeID: purgeID }; ReactPerf.measureMethods(ReactMount, 'ReactMount', { _renderNewRootComponent: '_renderNewRootComponent', _mountImageIntoNode: '_mountImageIntoNode' }); module.exports = ReactMount; }).call(this,require('_process')) },{"./DOMProperty":16,"./Object.assign":29,"./ReactBrowserEventEmitter":33,"./ReactCurrentOwner":41,"./ReactDOMFeatureFlags":46,"./ReactElement":59,"./ReactEmptyComponentRegistry":62,"./ReactInstanceHandles":68,"./ReactInstanceMap":69,"./ReactMarkupChecksum":71,"./ReactPerf":78,"./ReactReconciler":83,"./ReactUpdateQueue":89,"./ReactUpdates":90,"./instantiateReactComponent":125,"./setInnerHTML":131,"./shouldUpdateReactComponent":133,"./validateDOMNesting":135,"_process":164,"fbjs/lib/containsNode":140,"fbjs/lib/emptyObject":144,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],73:[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 ReactMultiChild * @typechecks static-only */ 'use strict'; var ReactComponentEnvironment = require('./ReactComponentEnvironment'); var ReactMultiChildUpdateTypes = require('./ReactMultiChildUpdateTypes'); var ReactCurrentOwner = require('./ReactCurrentOwner'); var ReactReconciler = require('./ReactReconciler'); var ReactChildReconciler = require('./ReactChildReconciler'); var flattenChildren = require('./flattenChildren'); /** * Updating children of a component may trigger recursive updates. The depth is * used to batch recursive updates to render markup more efficiently. * * @type {number} * @private */ var updateDepth = 0; /** * Queue of update configuration objects. * * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. * * @type {array<object>} * @private */ var updateQueue = []; /** * Queue of markup to be rendered. * * @type {array<string>} * @private */ var markupQueue = []; /** * Enqueues markup to be rendered and inserted at a supplied index. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function enqueueInsertMarkup(parentID, markup, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex: markupQueue.push(markup) - 1, content: null, fromIndex: null, toIndex: toIndex }); } /** * Enqueues moving an existing element to another index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function enqueueMove(parentID, fromIndex, toIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex: null, content: null, fromIndex: fromIndex, toIndex: toIndex }); } /** * Enqueues removing an element at an index. * * @param {string} parentID ID of the parent component. * @param {number} fromIndex Index of the element to remove. * @private */ function enqueueRemove(parentID, fromIndex) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex: null, content: null, fromIndex: fromIndex, toIndex: null }); } /** * Enqueues setting the markup of a node. * * @param {string} parentID ID of the parent component. * @param {string} markup Markup that renders into an element. * @private */ function enqueueSetMarkup(parentID, markup) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.SET_MARKUP, markupIndex: null, content: markup, fromIndex: null, toIndex: null }); } /** * Enqueues setting the text content. * * @param {string} parentID ID of the parent component. * @param {string} textContent Text content to set. * @private */ function enqueueTextContent(parentID, textContent) { // NOTE: Null values reduce hidden classes. updateQueue.push({ parentID: parentID, parentNode: null, type: ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex: null, content: textContent, fromIndex: null, toIndex: null }); } /** * Processes any enqueued updates. * * @private */ function processQueue() { if (updateQueue.length) { ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue); clearQueue(); } } /** * Clears any enqueued updates. * * @private */ function clearQueue() { updateQueue.length = 0; markupQueue.length = 0; } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) { var nextChildren; if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements); } finally { ReactCurrentOwner.current = null; } return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); } } nextChildren = flattenChildren(nextNestedChildrenElements); return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context); }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); child._mountIndex = index++; mountImages.push(mountImage); } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); // TODO: The setTextContent operation should be enough for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChild(prevChildren[name]); } } // Set new text content. this.setTextContent(nextContent); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { updateDepth++; var errorThrown = true; try { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { this._unmountChildByName(prevChildren[name], name); } } this.setMarkup(nextMarkup); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { updateDepth++; var errorThrown = true; try { this._updateChildren(nextNestedChildrenElements, transaction, context); errorThrown = false; } finally { updateDepth--; if (!updateDepth) { if (errorThrown) { clearQueue(); } else { processQueue(); } } } }, /** * Improve performance by isolating this hot code path from the try/catch * block in `updateChildren`. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context); this._renderedChildren = nextChildren; if (!nextChildren && !prevChildren) { return; } var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { this.moveChild(prevChild, nextIndex, lastIndex); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); this._unmountChild(prevChild); } // The child must be instantiated before it's mounted. this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context); } nextIndex++; } // Remove children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { this._unmountChild(prevChildren[name]); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @internal */ unmountChildren: function () { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { enqueueMove(this._rootNodeID, child._mountIndex, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, mountImage) { enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child) { enqueueRemove(this._rootNodeID, child._mountIndex); }, /** * Sets this text content string. * * @param {string} textContent Text content to set. * @protected */ setTextContent: function (textContent) { enqueueTextContent(this._rootNodeID, textContent); }, /** * Sets this markup string. * * @param {string} markup Markup to set. * @protected */ setMarkup: function (markup) { enqueueSetMarkup(this._rootNodeID, markup); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildByNameAtIndex: function (child, name, index, transaction, context) { // Inlined for performance, see `ReactInstanceHandles.createReactID`. var rootID = this._rootNodeID + name; var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context); child._mountIndex = index; this.createChild(child, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child) { this.removeChild(child); child._mountIndex = null; } } }; module.exports = ReactMultiChild; }).call(this,require('_process')) },{"./ReactChildReconciler":34,"./ReactComponentEnvironment":39,"./ReactCurrentOwner":41,"./ReactMultiChildUpdateTypes":74,"./ReactReconciler":83,"./flattenChildren":116,"_process":164}],74:[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('fbjs/lib/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, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; },{"fbjs/lib/keyMirror":154}],75:[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('fbjs/lib/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); } }; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if (typeof element.type === 'function') { return element.type; } var tag = element.type; var componentClass = tagToComponentClass[tag]; if (componentClass == null) { tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); } return componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined; return new genericComponentClass(element.type, element.props); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; }).call(this,require('_process')) },{"./Object.assign":29,"_process":164,"fbjs/lib/invariant":151}],76:[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 ReactNoopUpdateQueue */ 'use strict'; var warning = require('fbjs/lib/warning'); function warnTDZ(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnTDZ(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnTDZ(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnTDZ(publicInstance, 'setState'); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function (publicInstance, partialProps) { warnTDZ(publicInstance, 'setProps'); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function (publicInstance, props) { warnTDZ(publicInstance, 'replaceProps'); } }; module.exports = ReactNoopUpdateQueue; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/warning":162}],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 ReactOwner */ 'use strict'; var invariant = require('fbjs/lib/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) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined; // Check that `component` is still the current ref because we do not want to // detach the ref if another component stole it. if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/invariant":151}],78:[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 (process.env.NODE_ENV !== 'production') { for (var key in methodNames) { if (!methodNames.hasOwnProperty(key)) { continue; } object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]); } } }, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function (objName, fnName, func) { if (process.env.NODE_ENV !== 'production') { var measuredFunc = null; var wrapper = function () { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function (measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; }).call(this,require('_process')) },{"_process":164}],79:[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 (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; }).call(this,require('_process')) },{"_process":164}],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 ReactPropTypeLocations */ 'use strict'; var keyMirror = require('fbjs/lib/keyMirror'); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; },{"fbjs/lib/keyMirror":154}],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 ReactPropTypes */ 'use strict'; var ReactElement = require('./ReactElement'); var ReactPropTypeLocationNames = require('./ReactPropTypeLocationNames'); var emptyFunction = require('fbjs/lib/emptyFunction'); var getIteratorFn = require('./getIteratorFn'); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']'); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOf, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (propValue === expectedValues[i]) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOfType, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return '<<anonymous>>'; } return propValue.constructor.name; } module.exports = ReactPropTypes; },{"./ReactElement":59,"./ReactPropTypeLocationNames":79,"./getIteratorFn":122,"fbjs/lib/emptyFunction":143}],82:[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 ReactDOMFeatureFlags = require('./ReactDOMFeatureFlags'); var ReactInputSelection = require('./ReactInputSelection'); 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 occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(forceHTML) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; },{"./CallbackQueue":12,"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33,"./ReactDOMFeatureFlags":46,"./ReactInputSelection":67,"./Transaction":107}],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 ReactReconciler */ 'use strict'; var ReactRef = require('./ReactRef'); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, rootID, transaction, context) { var markup = internalInstance.mountComponent(rootID, transaction, context); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } return markup; }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance) { ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(); }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction) { internalInstance.performUpdateIfNecessary(transaction); } }; module.exports = ReactReconciler; },{"./ReactRef":84}],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 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) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; return( // This has a few false positives w/r/t empty components. prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref ); }; ReactRef.detachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; },{"./ReactOwner":77}],85:[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; },{}],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 ReactServerBatchingStrategy * @typechecks */ 'use strict'; var ReactServerBatchingStrategy = { isBatchingUpdates: false, batchedUpdates: function (callback) { // Don't do anything here. During the server rendering we don't want to // schedule any updates. We will simply ignore them. } }; module.exports = ReactServerBatchingStrategy; },{}],87:[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 ReactDefaultBatchingStrategy = require('./ReactDefaultBatchingStrategy'); var ReactElement = require('./ReactElement'); var ReactInstanceHandles = require('./ReactInstanceHandles'); var ReactMarkupChecksum = require('./ReactMarkupChecksum'); var ReactServerBatchingStrategy = require('./ReactServerBatchingStrategy'); var ReactServerRenderingTransaction = require('./ReactServerRenderingTransaction'); var ReactUpdates = require('./ReactUpdates'); var emptyObject = require('fbjs/lib/emptyObject'); var instantiateReactComponent = require('./instantiateReactComponent'); var invariant = require('fbjs/lib/invariant'); /** * @param {ReactElement} element * @return {string} the HTML markup */ function renderToString(element) { !ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); var markup = componentInstance.mountComponent(id, transaction, emptyObject); return ReactMarkupChecksum.addChecksumToMarkup(markup); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } /** * @param {ReactElement} element * @return {string} the HTML markup, without the extra React ID and checksum * (for generating static pages) */ function renderToStaticMarkup(element) { !ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined; var transaction; try { ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy); var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(true); return transaction.perform(function () { var componentInstance = instantiateReactComponent(element, null); return componentInstance.mountComponent(id, transaction, emptyObject); }, null); } finally { ReactServerRenderingTransaction.release(transaction); // Revert to the DOM batching strategy since these two renderers // currently share these stateful modules. ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy); } } module.exports = { renderToString: renderToString, renderToStaticMarkup: renderToStaticMarkup }; }).call(this,require('_process')) },{"./ReactDefaultBatchingStrategy":55,"./ReactElement":59,"./ReactInstanceHandles":68,"./ReactMarkupChecksum":71,"./ReactServerBatchingStrategy":86,"./ReactServerRenderingTransaction":88,"./ReactUpdates":90,"./instantiateReactComponent":125,"_process":164,"fbjs/lib/emptyObject":144,"fbjs/lib/invariant":151}],88:[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 Transaction = require('./Transaction'); var assign = require('./Object.assign'); var emptyFunction = require('fbjs/lib/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 }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = false; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap procedures. */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"./CallbackQueue":12,"./Object.assign":29,"./PooledClass":30,"./Transaction":107,"fbjs/lib/emptyFunction":143}],89:[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 ReactCurrentOwner = require('./ReactCurrentOwner'); var ReactElement = require('./ReactElement'); var ReactInstanceMap = require('./ReactInstanceMap'); var ReactUpdates = require('./ReactUpdates'); var assign = require('./Object.assign'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if (process.env.NODE_ENV !== 'production') { // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. process.env.NODE_ENV !== 'production' ? warning(!callerName, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor.displayName) : undefined; } return null; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) { !(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { !(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined; if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, /** * Sets a subset of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialProps Subset of the next props. * @internal */ enqueueSetProps: function (publicInstance, partialProps) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps'); if (!internalInstance) { return; } ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps); }, enqueueSetPropsInternal: function (internalInstance, partialProps) { var topLevelWrapper = internalInstance._topLevelWrapper; !topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; // Merge with the pending element if it exists, otherwise with existing // element props. var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; var element = wrapElement.props; var props = assign({}, element.props, partialProps); topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); enqueueUpdate(topLevelWrapper); }, /** * Replaces all of the props. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} props New props. * @internal */ enqueueReplaceProps: function (publicInstance, props) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps'); if (!internalInstance) { return; } ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props); }, enqueueReplacePropsInternal: function (internalInstance, props) { var topLevelWrapper = internalInstance._topLevelWrapper; !topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined; // Merge with the pending element if it exists, otherwise with existing // element props. var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement; var element = wrapElement.props; topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props)); enqueueUpdate(topLevelWrapper); }, enqueueElementInternal: function (internalInstance, newElement) { internalInstance._pendingElement = newElement; enqueueUpdate(internalInstance); } }; module.exports = ReactUpdateQueue; }).call(this,require('_process')) },{"./Object.assign":29,"./ReactCurrentOwner":41,"./ReactElement":59,"./ReactInstanceMap":69,"./ReactUpdates":90,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],90:[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 ReactPerf = require('./ReactPerf'); var ReactReconciler = require('./ReactReconciler'); var Transaction = require('./Transaction'); var assign = require('./Object.assign'); var invariant = require('fbjs/lib/invariant'); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false); } assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined; !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; }).call(this,require('_process')) },{"./CallbackQueue":12,"./Object.assign":29,"./PooledClass":30,"./ReactPerf":78,"./ReactReconciler":83,"./Transaction":107,"_process":164,"fbjs/lib/invariant":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 ReactVersion */ 'use strict'; module.exports = '0.14.6'; },{}],92:[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 */ 'use strict'; var DOMProperty = require('./DOMProperty'); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; var SVGDOMPropertyConfig = { Properties: { clipPath: MUST_USE_ATTRIBUTE, cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, fill: MUST_USE_ATTRIBUTE, fillOpacity: MUST_USE_ATTRIBUTE, fontFamily: MUST_USE_ATTRIBUTE, fontSize: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, markerEnd: MUST_USE_ATTRIBUTE, markerMid: MUST_USE_ATTRIBUTE, markerStart: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, opacity: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, preserveAspectRatio: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, stopColor: MUST_USE_ATTRIBUTE, stopOpacity: MUST_USE_ATTRIBUTE, stroke: MUST_USE_ATTRIBUTE, strokeDasharray: MUST_USE_ATTRIBUTE, strokeLinecap: MUST_USE_ATTRIBUTE, strokeOpacity: MUST_USE_ATTRIBUTE, strokeWidth: MUST_USE_ATTRIBUTE, textAnchor: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, xlinkActuate: MUST_USE_ATTRIBUTE, xlinkArcrole: MUST_USE_ATTRIBUTE, xlinkHref: MUST_USE_ATTRIBUTE, xlinkRole: MUST_USE_ATTRIBUTE, xlinkShow: MUST_USE_ATTRIBUTE, xlinkTitle: MUST_USE_ATTRIBUTE, xlinkType: MUST_USE_ATTRIBUTE, xmlBase: MUST_USE_ATTRIBUTE, xmlLang: MUST_USE_ATTRIBUTE, xmlSpace: MUST_USE_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE }, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: { clipPath: 'clip-path', fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', patternContentUnits: 'patternContentUnits', patternUnits: 'patternUnits', preserveAspectRatio: 'preserveAspectRatio', spreadMethod: 'spreadMethod', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlLang: 'xml:lang', xmlSpace: 'xml:space' } }; module.exports = SVGDOMPropertyConfig; },{"./DOMProperty":16}],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 SelectEventPlugin */ 'use strict'; var EventConstants = require('./EventConstants'); var EventPropagators = require('./EventPropagators'); var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); var ReactInputSelection = require('./ReactInputSelection'); var SyntheticEvent = require('./SyntheticEvent'); var getActiveElement = require('fbjs/lib/getActiveElement'); var isTextInputElement = require('./isTextInputElement'); var keyOf = require('fbjs/lib/keyOf'); var shallowEqual = require('fbjs/lib/shallowEqual'); var topLevelTypes = EventConstants.topLevelTypes; var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] } }; var activeElement = null; var activeElementID = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. var hasListener = false; var ON_SELECT_KEY = keyOf({ onSelect: null }); /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') { activeElement = topLevelTarget; activeElementID = topLevelTargetID; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementID = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) { break; } // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (id, registrationName, listener) { if (registrationName === ON_SELECT_KEY) { hasListener = true; } } }; module.exports = SelectEventPlugin; },{"./EventConstants":21,"./EventPropagators":25,"./ReactInputSelection":67,"./SyntheticEvent":99,"./isTextInputElement":127,"fbjs/lib/ExecutionEnvironment":137,"fbjs/lib/getActiveElement":146,"fbjs/lib/keyOf":155,"fbjs/lib/shallowEqual":160}],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 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; },{}],95:[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 EventListener = require('fbjs/lib/EventListener'); var EventPropagators = require('./EventPropagators'); var ReactMount = require('./ReactMount'); 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 emptyFunction = require('fbjs/lib/emptyFunction'); var getEventCharCode = require('./getEventCharCode'); var invariant = require('fbjs/lib/invariant'); var keyOf = require('fbjs/lib/keyOf'); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: true }), captured: keyOf({ onAbortCapture: true }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: true }), captured: keyOf({ onBlurCapture: true }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: true }), captured: keyOf({ onCanPlayCapture: true }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: true }), captured: keyOf({ onCanPlayThroughCapture: true }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: true }), captured: keyOf({ onClickCapture: true }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: true }), captured: keyOf({ onContextMenuCapture: true }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: true }), captured: keyOf({ onCopyCapture: true }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: true }), captured: keyOf({ onCutCapture: true }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: true }), captured: keyOf({ onDoubleClickCapture: true }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: true }), captured: keyOf({ onDragCapture: true }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: true }), captured: keyOf({ onDragEndCapture: true }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: true }), captured: keyOf({ onDragEnterCapture: true }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: true }), captured: keyOf({ onDragExitCapture: true }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: true }), captured: keyOf({ onDragLeaveCapture: true }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: true }), captured: keyOf({ onDragOverCapture: true }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: true }), captured: keyOf({ onDragStartCapture: true }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: true }), captured: keyOf({ onDropCapture: true }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: true }), captured: keyOf({ onDurationChangeCapture: true }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: true }), captured: keyOf({ onEmptiedCapture: true }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: true }), captured: keyOf({ onEncryptedCapture: true }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: true }), captured: keyOf({ onEndedCapture: true }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: true }), captured: keyOf({ onErrorCapture: true }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: true }), captured: keyOf({ onFocusCapture: true }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: true }), captured: keyOf({ onInputCapture: true }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: true }), captured: keyOf({ onKeyDownCapture: true }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: true }), captured: keyOf({ onKeyPressCapture: true }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: true }), captured: keyOf({ onKeyUpCapture: true }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: true }), captured: keyOf({ onLoadCapture: true }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: true }), captured: keyOf({ onLoadedDataCapture: true }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: true }), captured: keyOf({ onLoadedMetadataCapture: true }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: true }), captured: keyOf({ onLoadStartCapture: true }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: true }), captured: keyOf({ onMouseDownCapture: true }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: true }), captured: keyOf({ onMouseMoveCapture: true }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: true }), captured: keyOf({ onMouseOutCapture: true }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: true }), captured: keyOf({ onMouseOverCapture: true }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: true }), captured: keyOf({ onMouseUpCapture: true }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: true }), captured: keyOf({ onPasteCapture: true }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: true }), captured: keyOf({ onPauseCapture: true }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: true }), captured: keyOf({ onPlayCapture: true }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: true }), captured: keyOf({ onPlayingCapture: true }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: true }), captured: keyOf({ onProgressCapture: true }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: true }), captured: keyOf({ onRateChangeCapture: true }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: true }), captured: keyOf({ onResetCapture: true }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: true }), captured: keyOf({ onScrollCapture: true }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: true }), captured: keyOf({ onSeekedCapture: true }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: true }), captured: keyOf({ onSeekingCapture: true }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: true }), captured: keyOf({ onStalledCapture: true }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: true }), captured: keyOf({ onSubmitCapture: true }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: true }), captured: keyOf({ onSuspendCapture: true }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: true }), captured: keyOf({ onTimeUpdateCapture: true }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: true }), captured: keyOf({ onTouchCancelCapture: true }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: true }), captured: keyOf({ onTouchEndCapture: true }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: true }), captured: keyOf({ onTouchMoveCapture: true }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: true }), captured: keyOf({ onTouchStartCapture: true }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: true }), captured: keyOf({ onVolumeChangeCapture: true }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: true }), captured: keyOf({ onWaitingCapture: true }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: true }), captured: keyOf({ onWheelCapture: true }) } } }; var topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var ON_CLICK_KEY = keyOf({ onClick: null }); var onClickListeners = {}; var SimpleEventPlugin = { eventTypes: eventTypes, /** * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @see {EventPluginHub.extractEvents} */ extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // FireFox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined; var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (id, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var node = ReactMount.getNode(id); if (!onClickListeners[id]) { onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (id, registrationName) { if (registrationName === ON_CLICK_KEY) { onClickListeners[id].remove(); delete onClickListeners[id]; } } }; module.exports = SimpleEventPlugin; }).call(this,require('_process')) },{"./EventConstants":21,"./EventPropagators":25,"./ReactMount":72,"./SyntheticClipboardEvent":96,"./SyntheticDragEvent":98,"./SyntheticEvent":99,"./SyntheticFocusEvent":100,"./SyntheticKeyboardEvent":102,"./SyntheticMouseEvent":103,"./SyntheticTouchEvent":104,"./SyntheticUIEvent":105,"./SyntheticWheelEvent":106,"./getEventCharCode":118,"_process":164,"fbjs/lib/EventListener":136,"fbjs/lib/emptyFunction":143,"fbjs/lib/invariant":151,"fbjs/lib/keyOf":155}],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 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, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; },{"./SyntheticEvent":99}],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 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, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; },{"./SyntheticEvent":99}],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 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, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; },{"./SyntheticMouseEvent":103}],99:[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 SyntheticEvent * @typechecks static-only */ 'use strict'; var PooledClass = require('./PooledClass'); var assign = require('./Object.assign'); var emptyFunction = require('fbjs/lib/emptyFunction'); var warning = require('fbjs/lib/warning'); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. */ function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { this.dispatchConfig = dispatchConfig; this.dispatchMarker = dispatchMarker; this.nativeEvent = nativeEvent; this.target = nativeEventTarget; this.currentTarget = nativeEventTarget; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { this[propName] = nativeEvent[propName]; } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; } assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; } if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined; } if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { this[propName] = null; } this.dispatchConfig = null; this.dispatchMarker = null; this.nativeEvent = null; } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var prototype = Object.create(Super.prototype); assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; }).call(this,require('_process')) },{"./Object.assign":29,"./PooledClass":30,"_process":164,"fbjs/lib/emptyFunction":143,"fbjs/lib/warning":162}],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 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, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; },{"./SyntheticUIEvent":105}],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 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, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; },{"./SyntheticEvent":99}],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 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, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; },{"./SyntheticUIEvent":105,"./getEventCharCode":118,"./getEventKey":119,"./getEventModifierState":120}],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 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, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; },{"./SyntheticUIEvent":105,"./ViewportMetrics":108,"./getEventModifierState":120}],104:[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, nativeEventTarget) { SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; },{"./SyntheticUIEvent":105,"./getEventModifierState":120}],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 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, nativeEventTarget) { SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; },{"./SyntheticEvent":99,"./getEventTarget":121}],106:[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, nativeEventTarget) { SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; },{"./SyntheticMouseEvent":103}],107:[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('fbjs/lib/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.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/invariant":151}],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 ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{}],109:[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('fbjs/lib/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) { !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; }).call(this,require('_process')) },{"_process":164,"fbjs/lib/invariant":151}],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 adler32 */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { for (; i < Math.min(i + 4096, m); i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; },{}],111:[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 canDefineProperty */ 'use strict'; var canDefineProperty = false; if (process.env.NODE_ENV !== 'production') { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; }).call(this,require('_process')) },{"_process":164}],112:[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":10}],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 deprecated */ 'use strict'; var assign = require('./Object.assign'); var warning = require('fbjs/lib/warning'); /** * This will log a single deprecation notice per function and forward the call * on to the new API. * * @param {string} fnName The name of the function * @param {string} newModule The module that fn will exist in * @param {string} newPackage The module that fn will exist in * @param {*} ctx The context this forwarded call should run in * @param {function} fn The function to forward on to * @return {function} The function that will warn once and then call fn */ function deprecated(fnName, newModule, newPackage, ctx, fn) { var warned = false; if (process.env.NODE_ENV !== 'production') { var newFn = function () { process.env.NODE_ENV !== 'production' ? warning(warned, // Require examples in this string must be split to prevent React's // build tools from mistaking them for real requires. // Otherwise the build tools will attempt to build a '%s' module. 'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined; warned = true; return fn.apply(ctx, arguments); }; // We need to make sure all properties of the original fn are copied over. // In particular, this is needed to support PropTypes return assign(newFn, fn); } return fn; } module.exports = deprecated; }).call(this,require('_process')) },{"./Object.assign":29,"_process":164,"fbjs/lib/warning":162}],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 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; },{}],115:[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('fbjs/lib/invariant'); var warning = require('fbjs/lib/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 (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } if (ReactInstanceMap.has(componentOrElement)) { return ReactMount.getNodeFromInstance(componentOrElement); } !(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined; !false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined; } module.exports = findDOMNode; }).call(this,require('_process')) },{"./ReactCurrentOwner":41,"./ReactInstanceMap":69,"./ReactMount":72,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],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 flattenChildren */ 'use strict'; var traverseAllChildren = require('./traverseAllChildren'); var warning = require('fbjs/lib/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[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined; } if (keyUnique && child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; }).call(this,require('_process')) },{"./traverseAllChildren":134,"_process":164,"fbjs/lib/warning":162}],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 forEachAccumulated */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function (arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],118:[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 {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; },{}],119:[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":118}],120:[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) { 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; },{}],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 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; },{}],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 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; },{}],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 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; },{}],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 getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = require('fbjs/lib/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; },{"fbjs/lib/ExecutionEnvironment":137}],125:[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('fbjs/lib/invariant'); var warning = require('fbjs/lib/warning'); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function () {}; assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node) { var instance; if (node === null || node === false) { instance = new ReactEmptyComponent(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined; // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined; } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if (process.env.NODE_ENV !== 'production') { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (process.env.NODE_ENV !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; }).call(this,require('_process')) },{"./Object.assign":29,"./ReactCompositeComponent":40,"./ReactEmptyComponent":61,"./ReactNativeComponent":75,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],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 isEventSupported */ 'use strict'; var ExecutionEnvironment = require('fbjs/lib/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; },{"fbjs/lib/ExecutionEnvironment":137}],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 isTextInputElement */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); } module.exports = isTextInputElement; },{}],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 onlyChild */ 'use strict'; var ReactElement = require('./ReactElement'); var invariant = require('fbjs/lib/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) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined; return children; } module.exports = onlyChild; }).call(this,require('_process')) },{"./ReactElement":59,"_process":164,"fbjs/lib/invariant":151}],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 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":114}],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 renderSubtreeIntoContainer */ 'use strict'; var ReactMount = require('./ReactMount'); module.exports = ReactMount.renderSubtreeIntoContainer; },{"./ReactMount":72}],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 setInnerHTML */ /* globals MSApp */ 'use strict'; var ExecutionEnvironment = require('fbjs/lib/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. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } } module.exports = setInnerHTML; },{"fbjs/lib/ExecutionEnvironment":137}],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 setTextContent */ 'use strict'; var ExecutionEnvironment = require('fbjs/lib/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; },{"./escapeTextContentForBrowser":114,"./setInnerHTML":131,"fbjs/lib/ExecutionEnvironment":137}],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 shouldUpdateReactComponent * @typechecks static-only */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } return false; } module.exports = shouldUpdateReactComponent; },{}],134:[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 ReactCurrentOwner = require('./ReactCurrentOwner'); var ReactElement = require('./ReactElement'); var ReactInstanceHandles = require('./ReactInstanceHandles'); var getIteratorFn = require('./getIteratorFn'); var invariant = require('fbjs/lib/invariant'); var warning = require('fbjs/lib/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 {*} text Component key to be escaped. * @return {string} An escaped string. */ function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper); } /** * Wrap a `key` value explicitly provided by the user to distinguish it from * implicitly-generated keys generated by a component's index in its parent. * * @param {string} key Value of a user-provided `key` attribute * @return {string} */ function wrapUserProvidedKey(key) { return '$' + escapeUserProvidedKey(key); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); !false ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; }).call(this,require('_process')) },{"./ReactCurrentOwner":41,"./ReactElement":59,"./ReactInstanceHandles":68,"./getIteratorFn":122,"_process":164,"fbjs/lib/invariant":151,"fbjs/lib/warning":162}],135:[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 validateDOMNesting */ 'use strict'; var assign = require('./Object.assign'); var emptyFunction = require('fbjs/lib/emptyFunction'); var warning = require('fbjs/lib/warning'); var validateDOMNesting = emptyFunction; if (process.env.NODE_ENV !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { parentTag: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.parentTag = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dialog': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'main': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': case 'pre': case 'listing': case 'table': case 'hr': case 'xmp': case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; /*eslint-disable space-after-keywords */ do { /*eslint-enable space-after-keywords */ stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.parentTag; var parentTag = parentInfo && parentInfo.tag; var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined; } } }; validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2); validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.parentTag; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; }).call(this,require('_process')) },{"./Object.assign":29,"_process":164,"fbjs/lib/emptyFunction":143,"fbjs/lib/warning":162}],136:[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 */ 'use strict'; 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) { target.addEventListener(eventType, callback, true); return { remove: function () { target.removeEventListener(eventType, callback, true); } }; } else { if (process.env.NODE_ENV !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function () {} }; module.exports = EventListener; }).call(this,require('_process')) },{"./emptyFunction":143,"_process":164}],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 ExecutionEnvironment */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],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 camelize * @typechecks */ "use strict"; var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; },{}],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 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":138}],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 containsNode * @typechecks */ 'use strict'; var isTextNode = require('./isTextNode'); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(_x, _x2) { var _again = true; _function: while (_again) { var outerNode = _x, innerNode = _x2; _again = false; if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { _x = outerNode; _x2 = innerNode.parentNode; _again = true; continue _function; } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } } module.exports = containsNode; },{"./isTextNode":153}],141:[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 */ 'use strict'; 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 Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; },{"./toArray":161}],142:[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 */ /*eslint-disable fb-www/unsafe-html*/ 'use strict'; 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; !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = createArrayFromMixed(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; }).call(this,require('_process')) },{"./ExecutionEnvironment":137,"./createArrayFromMixed":141,"./getMarkupWrap":147,"./invariant":151,"_process":164}],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 emptyFunction */ "use strict"; function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; },{}],144:[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 (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; }).call(this,require('_process')) },{"_process":164}],145:[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 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; },{}],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 getActiveElement * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ 'use strict'; function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; },{}],147:[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 */ /*eslint-disable fb-www/unsafe-html */ 'use strict'; 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 = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; }).call(this,require('_process')) },{"./ExecutionEnvironment":137,"./invariant":151,"_process":164}],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 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; },{}],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 hyphenate * @typechecks */ 'use strict'; var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; },{}],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 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":149}],151:[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. */ function invariant(condition, format, a, b, c, d, e, f) { if (process.env.NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; }).call(this,require('_process')) },{"_process":164}],152:[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. */ 'use strict'; function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; },{}],153:[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 */ 'use strict'; 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":152}],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 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; !(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; }).call(this,require('_process')) },{"./invariant":151,"_process":164}],155:[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 losing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ "use strict"; var keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],156:[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; },{}],157:[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; },{}],158:[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":137}],159:[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 */ 'use strict'; var performance = require('./performance'); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function () { return performance.now(); }; } else { performanceNow = function () { return Date.now(); }; } module.exports = performanceNow; },{"./performance":158}],160:[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 * @typechecks * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; },{}],161:[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 toArray * @typechecks */ 'use strict'; 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). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined; !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined; !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } module.exports = toArray; }).call(this,require('_process')) },{"./invariant":151,"_process":164}],162:[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 (process.env.NODE_ENV !== 'production') { warning = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} } }; } module.exports = warning; }).call(this,require('_process')) },{"./emptyFunction":143,"_process":164}],163:[function(require,module,exports){ 'use strict'; module.exports = require('./lib/React'); },{"./lib/React":31}],164:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],165:[function(require,module,exports){ var React = require('react'); var LocationForm = require('./LocationForm'); var LocationList = require('./LocationList'); var LocationBox = React.createClass({displayName: "LocationBox", handleLocationAdd: function (newLoc) { console.log("location add", newLoc); var newLocations = this.props.locations.concat([newLoc]); this.props.stateHandler({ locations: newLocations, searchBoxValue: "" }, '/api/weather/location/add', 'POST', newLoc); }, handleLocationDelete: function (locationId) { var newLocations = this.props.locations.filter(function(loc){ return loc.locId !== locationId; }); this.props.stateHandler({ locations: newLocations }, '/api/weather/location/delete', 'POST', { id: locationId }); }, handleLocationSelect: function(index) { //set all locations as unselected var newLocations = this.props.locations.map(function (location) { location.selected = false; return location; }); //"select" the single location newLocations[index].selected = 'true'; this.props.stateHandler({ locations: newLocations, selectedLocation: newLocations[index] }); }, render: function () { return ( React.createElement("div", {className: "locationBox col-md-4"}, React.createElement("h3", null, "Locations"), React.createElement(LocationForm, { addLocClick: this.handleLocationAdd, searchBoxValue: this.props.searchBoxValue} ), React.createElement(LocationList, { className: "location-list", locations: this.props.locations, deleteHandler: this.handleLocationDelete, makeSelected: this.handleLocationSelect} ) ) ) } }); module.exports = LocationBox; },{"./LocationForm":167,"./LocationList":168,"react":163}],166:[function(require,module,exports){ var React = require('react'); var WeatherHeader = require('./WeatherHeader') var LocationDashboard = React.createClass({displayName: "LocationDashboard", render: function () { return ( React.createElement("div", {className: "col-md-8"}, React.createElement(WeatherHeader, { locationTitle: this.props.weatherData.title, currently: this.props.weatherData.currently} ), React.createElement("div", {id: "tabs", className: "tabbable"}, React.createElement("ul", {className: "nav nav-tabs"}, React.createElement("li", {className: "active"}, React.createElement("a", {href: "#panel-806764", "data-toggle": "tab"}, "Forecast")) ), React.createElement("div", {className: "tab-content"}, React.createElement("div", {id: "panel-806764", className: "tab-pane active"}, React.createElement("p", {dangerouslySetInnerHTML: {__html:this.props.weatherData.description}}) ) ) ) ) ) } }); module.exports = LocationDashboard; },{"./WeatherHeader":170,"react":163}],167:[function(require,module,exports){ var React = require('react'), Autosuggest = require('react-autosuggest'); var LocationForm = React.createClass({displayName: "LocationForm", getSuggestions: function (input, callback) { $.get('/api/weather/locationsearch/' + input, function(suggestions) { setTimeout(callback(null, suggestions.predictions), 300); // Emulate API call }.bind(this)); }, renderSuggestion: function (suggestion, input) { // In this example, 'suggestion' is a string return ( // and it returns a ReactElement React.createElement("span", null, suggestion.description) ); }, onSuggestionSelected: function(suggestion, event) { setTimeout(function(){ $('.react-autosuggest input').val(''); },100) this.props.addLocClick(suggestion); }, getSuggestionValue: function (suggestionObj) { return suggestionObj.description; }, render: function () { return ( React.createElement("div", {className: "form-group"}, React.createElement(Autosuggest, { className: "form-control", id: "search-box", type: "text", focusInputOnSuggestionClick: false, value: this.props.searchBoxValue, suggestions: this.getSuggestions, suggestionRenderer: this.renderSuggestion, onSuggestionSelected: this.onSuggestionSelected, suggestionValue: this.getSuggestionValue, showWhen: input => input.trim().length >= 3} ) ) ) } }); module.exports = LocationForm; },{"react":163,"react-autosuggest":1}],168:[function(require,module,exports){ var React = require('react'); var LocationListItem = require('./LocationListItem'); var LocationList = React.createClass({displayName: "LocationList", generateClass: function(selected) { var classes = { "panel-body": true, "selected": selected ? true : false }; var classArr = []; for(var propt in classes){ if (classes[propt]) classArr.push(propt); } return classArr.join(" "); }, render: function () { var locs = []; if (this.props.locations.length) { locs = this.props.locations.map(function(location, index) { location.classes = this.generateClass(location.selected); return ( React.createElement(LocationListItem, { locationName: location.description, locId: location.locId, key: location.locId, index: index, doDelete: this.props.deleteHandler, classes: location.classes, onSelectClick: this.props.makeSelected} ) ); }, this); } return ( React.createElement("div", {className: "panel panel-default"}, locs ) ) } }); module.exports = LocationList; },{"./LocationListItem":169,"react":163}],169:[function(require,module,exports){ var React = require('react'); // var classNames = require( 'classnames' ); var LocationListItem = React.createClass({displayName: "LocationListItem", doDelete: function (locationId, e) { console.log('do delete'); var proceed = confirm("Are you sure you want to delete this location?"); if (proceed) this.props.doDelete(locationId); }, render: function () { var locationName = this.props.locationName; return ( React.createElement("div", {className: this.props.classes}, React.createElement("span", {className: "deleteBtn", onClick: this.doDelete.bind(null, this.props.locId)}, React.createElement("span", null, React.createElement("i", {className: "fa fa-2x fa-trash"}), " |" ) ), React.createElement("span", {onClick: this.props.onSelectClick.bind(null, this.props.index)}, this.props.locationName) ) ) } }); module.exports = LocationListItem; },{"react":163}],170:[function(require,module,exports){ var React = require('react'); var WeatherHeader = React.createClass({displayName: "WeatherHeader", render: function () { return ( React.createElement("div", null, React.createElement("h3", null, this.props.locationTitle), React.createElement("p", {className: "text-muted"}, React.createElement("em", null, this.props.currently) ) ) ) } }); module.exports = WeatherHeader; },{"react":163}],171:[function(require,module,exports){ var React = require('react'); var LocationBox = require('./LocationBox'); var LocationDashboard = require('./LocationDashboard'); var WeatherParent = React.createClass({displayName: "WeatherParent", getInitialState: function () { return { selectedLocation: "", searchBoxValue: "", weatherData: "", locations: [] }; }, stateHandler: function(newState, url, type, data) { //set state if the first arg isn't null if (newState !== null) { this.setState(newState); } //get weather data if selected Location just changed if ("selectedLocation" in newState) { console.log('placeId', newState.selectedLocation.placeId); $.get('api/weather/location/detail/' + newState.selectedLocation.placeId, function (googleLoc) { this.getWeatherData(googleLoc.result) }.bind(this)); } //return if a url is not passed (we only want to set state) if (!url) return; $.ajax({ type: type, url: url, contentType: 'application/json', // dataType: 'json', data: JSON.stringify(data), success: function(data){ if (data.weatherLocations) this.stateHandler({locations: data.weatherLocations}) }.bind(this) }); }, componentDidMount: function() { /** * When the component mounts, get a list of the user's locations */ $.get(this.props.source, function(result) { if (this.isMounted()) { this.setState({ locations: result ? result.weatherLocations : [] }); } }.bind(this)); }, componentDidUpdate: function(params) { // update event handler }, getWeatherData: function (location) { var latLong = location.geometry.location.lat + "," + location.geometry.location.lng $.simpleWeather({ location: latLong, unit: 'f', success: function(weather) { this.setState({weatherData: weather}); }.bind(this), error: function(error) { console.log('weather error', error); } }).bind(this); }, render: function () { return ( React.createElement("div", {className: "row"}, React.createElement(LocationBox, { locations: this.state.locations, stateHandler: this.stateHandler, searchBoxValue: this.state.searchBoxValue, getWeatherData: this.getWeatherData} ), React.createElement(LocationDashboard, { weatherData: this.state.weatherData} ) ) ) } }); module.exports = WeatherParent; },{"./LocationBox":165,"./LocationDashboard":166,"react":163}],172:[function(require,module,exports){ var ReactDOM = require('react-dom'); var React = require('react'); var WeatherParent = require('./WeatherParent'); var reactComponent = ReactDOM.render( React.createElement(WeatherParent, { source: "/api/weather/locations/get", delUrl: "/api/weather/locations/delete"} ), document.getElementById('weatherParent') ) // var reactComponent = ReactDOM.render( // <LocationBox // source="/api/weather/locations/get" // delUrl="/api/weather/locations/delete" // />, // <LocationDashboard/>, // document.getElementById('locationCol') // ) },{"./WeatherParent":171,"react":163,"react-dom":7}]},{},[172]);
benwells/admin.mrbenwells.com
public/js/weather/build/weatherapp.js
JavaScript
mit
709,898
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Landing from '../pages/Landing'; import { setAuthenticated } from '../actions/app'; export default function(ComposedComponent){ class Authenticate extends Component { setAuthenticated(state){ this.props.setAuthenticated(state); } componentWillMount(){ /* let location = window.location.pathname; console.log(location); let self = this; let userPool = this.props.app.aws.cognito.userPool; let cognitoUser = userPool.getCurrentUser(); if(cognitoUser !== null){ this.setAuthenticated(true); return } else { if(location == "/"){ return; } if(!location == "/"){ self.context.router.push("/login"); } } */ } componentWillUpdate(nextProps){ /* let location = window.location.pathname; let userPool = this.props.app.aws.cognito.userPool; let cognitoUser = userPool.getCurrentUser(); if(location == "/"){ return; } if(cognitoUser == null){ this.context.router.push("/login"); } */ } render(){ if(this.props.app.isAuthenticated === false){ return ( <ComposedComponent> <Landing { ...this.props } /> </ComposedComponent> ); } else { return ( <ComposedComponent> { this.props.children } </ComposedComponent> ); } } } const mapDispatchToProps = (dispatch) => { return { setAuthenticated: (state) => { dispatch(setAuthenticated(state)); }, setAWSCognitoUserPool: (userPoolId, clientId) => { let poolData = { UserPoolId: userPoolId, ClientId: clientId }; let userPool = new CognitoUserPool(poolData); dispatch(setAWSCognitoUserPool(userPool)); } }; }; function mapStateToProps(state, ownProps){ return { app: state.app }; } Authenticate.contextTypes = { router: React.PropTypes.object.isRequired }; return connect(mapStateToProps, mapDispatchToProps)(Authenticate); }
jeffersonsteelflex69/mytv
client/src/utils/AuthRequired.js
JavaScript
mit
2,006
var class_all_pawns_must_die_1_1_uci_init_command = [ [ "Execute", "class_all_pawns_must_die_1_1_uci_init_command.html#a05a5de2a2813a65504aa70b98a397f14", null ] ];
manixaist/AllPawnsMustDie
docs/html/class_all_pawns_must_die_1_1_uci_init_command.js
JavaScript
mit
168
/* eslint-disable func-names */ /* eslint quote-props: ["error", "consistent"]*/ "use strict"; const rp = require("request-promise-native"); const Alexa = require("alexa-sdk"); const beaufort = require("beaufort-scale"); const format = require("string-format"); const APP_ID = undefined; // TODO replace with your app ID (OPTIONAL). const languageStrings = { "en-GB": { translation: { SKILL_NAME: "British Weer", // current temp options GET_CURRENT_MESSAGE_FEELS_LIKE: "In {city} it is currently {currentTemp} degrees, but it feels like {currentFeelsLikeTemp}.", GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT: "In {city} it is currently {currentTemp} degrees.", GET_MAX_MIN_TEMP_MESSAGE: "The low for the rest of the day will be {dailyMinTemp} degrees with a high of {dailyMaxTemp} degrees.", GET_WIND_MESSAGE: "Wind is currently a {windType}.", GET_RAIN_MESSAGE_NOW: "There is a {rain.chanceOfRain} percent chance of rain this hour.", GET_RAIN_MESSAGE_FUTURE: "There is a {rain.chanceOfRain} percent chance of rain in around {rain.hoursUntilRain} hours.", GET_NO_RAIN_FOR_REST_OF_DAY: "There is no chance of rain for the rest of the day.", HELP_MESSAGE: "You can say tell me the weather, or, when is it going to rain. You can also just say quit. What can I help you with?", HELP_REPROMPT: "What can I help you with?", STOP_MESSAGE: "Goodbye!" } }, "en-US": { translation: { SKILL_NAME: "American Weer", // current temp options GET_CURRENT_MESSAGE_FEELS_LIKE: "In {city} it is currently {currentTemp} degrees, but it feels like {currentFeelsLikeTemp}.", GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT: "In {city} it is currently {currentTemp} degrees.", GET_MAX_MIN_TEMP_MESSAGE: "The low for the rest of the day will be {dailyMinTemp} degrees with a high of {dailyMaxTemp} degrees.", GET_WIND_MESSAGE: "Wind is currently a {windType}.", GET_RAIN_MESSAGE_NOW: "There is a {rain.chanceOfRain} percent chance of rain this hour.", GET_RAIN_MESSAGE_FUTURE: "There is a {rain.chanceOfRain} percent chance of rain in around {rain.hoursUntilRain} hours.", GET_NO_RAIN_FOR_REST_OF_DAY: "There is no chance of rain for the rest of the day.", HELP_MESSAGE: "You can say tell me the weather, or, when is it going to rain. You can also just say quit. What can I help you with?", HELP_REPROMPT: "What can I help you with?", STOP_MESSAGE: "Goodbye!" } } // 'de-DE': { // translation: { // FACTS: [ // 'Ein Jahr dauert auf dem Merkur nur 88 Tage.', // 'Die Venus ist zwar weiter von der Sonne entfernt, hat aber höhere Temperaturen als Merkur.', // 'Venus dreht sich entgegen dem Uhrzeigersinn, möglicherweise aufgrund eines früheren Zusammenstoßes mit einem Asteroiden.', // 'Auf dem Mars erscheint die Sonne nur halb so groß wie auf der Erde.', // 'Die Erde ist der einzige Planet, der nicht nach einem Gott benannt ist.', // 'Jupiter hat den kürzesten Tag aller Planeten.', // 'Die Milchstraßengalaxis wird in etwa 5 Milliarden Jahren mit der Andromeda-Galaxis zusammenstoßen.', // 'Die Sonne macht rund 99,86 % der Masse im Sonnensystem aus.', // 'Die Sonne ist eine fast perfekte Kugel.', // 'Eine Sonnenfinsternis kann alle ein bis zwei Jahre eintreten. Sie ist daher ein seltenes Ereignis.', // 'Der Saturn strahlt zweieinhalb mal mehr Energie in den Weltraum aus als er von der Sonne erhält.', // 'Die Temperatur in der Sonne kann 15 Millionen Grad Celsius erreichen.', // 'Der Mond entfernt sich von unserem Planeten etwa 3,8 cm pro Jahr.', // ], // SKILL_NAME: 'Weltraumwissen auf Deutsch', // GET_WEATHER_MESSAGE: 'Hier sind deine Fakten: ', // HELP_MESSAGE: 'Du kannst sagen, „Nenne mir einen Fakt über den Weltraum“, oder du kannst „Beenden“ sagen... Wie kann ich dir helfen?', // HELP_REPROMPT: 'Wie kann ich dir helfen?', // STOP_MESSAGE: 'Auf Wiedersehen!', // }, // }, }; const buienRaderForecast = function( forecast, hours_ahead_to_check_rain, rain_percent_threshold = 9 ) { const rain = (forecast, hours_ahead_to_check_rain) => { // the site only returns an hours array containing the amount of hours left depending on request time let hoursLeftInDay = Object.keys(forecast["days"][0]["hours"]).length; let hoursToCheck; // only go through the rest of the hours in the day, even if user asks for more if (hoursLeftInDay < hours_ahead_to_check_rain) { hoursToCheck = hoursLeftInDay; } else { hoursToCheck = hours_ahead_to_check_rain; } // find the hour when there is a chance of rain forecast["days"][0]["hours"].map((hour, rain_percent_threshold) => { let chanceOfRain = hour.precipation; if (chanceOfRain > rain_percent_threshold) { return { chanceOfRain: chanceOfRain, hoursUntilRain: i }; } }); return null; // there is no rain up coming }; let currentTemp = roundFloat(forecast["days"][0]["hours"][0]["temperature"]); let currentFeelsLikeTemp = roundFloat( forecast["days"][0]["hours"][0]["feeltemperature"] ); return { dailyMaxTemp: roundFloat(forecast["days"][0]["maxtemp"]), dailyMinTemp: roundFloat(forecast["days"][0]["mintemp"]), currentTemp: currentTemp, currentFeelsLikeTemp: currentFeelsLikeTemp, feelsLikeEqualCurrentTemp: currentTemp === currentFeelsLikeTemp, windType: beaufort( forecast["days"][0]["hours"][0]["windspeed"] ).desc.toLowerCase(), rain: rain(forecast, hours_ahead_to_check_rain) }; }; // round temperatures which come in as floats const roundFloat = float => { return Math.round(float); }; const handlers = { LaunchRequest: function() { this.emit("GetWeer"); }, GetWeerRainIntent: function() { let options = { uri: "https://api.buienradar.nl/data/forecast/1.1/all/2747596", json: true }; rp(options) .then(weather => { let forecast = buienRaderForecast(weather, 24, 0); forecast["city"] = "Schiedam"; let speechOut = []; // rain message if (forecast.rain) { speechOut.push( format( forecast.rain.hoursUntilRain > 0 ? this.t("GET_RAIN_MESSAGE_FUTURE") : this.t("GET_RAIN_MESSAGE_NOW"), forecast ) ); } else { speechOut.push(this.t("GET_NO_RAIN_FOR_REST_OF_DAY")); } this.emit( ":tellWithCard", speechOut.join(" "), this.t("SKILL_NAME"), speechOut.join(" ") ); }) .catch(err => { const speechOutput = "Failed to query for Weather information: " + err; this.emit( ":tellWithCard", speechOutput, this.t("SKILL_NAME"), speechOutput ); }); }, GetWeerIntent: function() { this.emit("GetWeer"); }, GetWeer: function() { let options = { uri: "https://api.buienradar.nl/data/forecast/1.1/all/2747596", json: true }; rp(options) .then(weather => { let forecast = buienRaderForecast(weather, 5); forecast["city"] = "Schiedam"; let speechOut = []; // get current temp speechOut.push( format( forecast.feelsLikeEqualCurrentTemp ? this.t("GET_CURRENT_MESSAGE_FEELS_LIKE_IS_CURRENT") : this.t("GET_CURRENT_MESSAGE_FEELS_LIKE"), forecast ) ); // min max temp message speechOut.push(format(this.t("GET_MAX_MIN_TEMP_MESSAGE"), forecast)); // wind message speechOut.push(format(this.t("GET_WIND_MESSAGE"), forecast)); // rain message if (forecast.rain) { speechOut.push( format( forecast.rain.hoursUntilRain > 0 ? this.t("GET_RAIN_MESSAGE_FUTURE") : this.t("GET_RAIN_MESSAGE_NOW"), forecast ) ); } this.emit( ":tellWithCard", speechOut.join(" "), this.t("SKILL_NAME"), speechOut.join(" ") ); }) .catch(err => { const speechOutput = "Failed to query for Weather information: " + err; this.emit( ":tellWithCard", speechOutput, this.t("SKILL_NAME"), speechOutput ); }); }, "AMAZON.HelpIntent": function() { const speechOutput = this.t("HELP_MESSAGE"); const reprompt = this.t("HELP_MESSAGE"); this.emit(":ask", speechOutput, reprompt); }, "AMAZON.CancelIntent": function() { this.emit(":tell", this.t("STOP_MESSAGE")); }, "AMAZON.StopIntent": function() { this.emit(":tell", this.t("STOP_MESSAGE")); }, SessionEndedRequest: function() { this.emit(":tell", this.t("STOP_MESSAGE")); } }; exports.handler = (event, context) => { const alexa = Alexa.handler(event, context); alexa.APP_ID = APP_ID; // To enable string internationalization (i18n) features, set a resources object. alexa.resources = languageStrings; alexa.registerHandlers(handlers); alexa.execute(); };
MattHodge/alexa
buienradar/src/index.js
JavaScript
mit
9,489
'use strict'; // Programs controller angular.module('programs').controller('ProgramsController', ['$scope', '$http', '$stateParams', '$location', 'Authentication', 'Programs', 'Comments', 'ProgramsComment', 'Likes', 'ProgramsLike', 'Search', function($scope, $http, $stateParams, $location, Authentication, Programs, Comments, ProgramsComment, Likes, ProgramsLike, Search) { $scope.authentication = Authentication; var geocoder; // SearchResults for Programs $scope.searchResults = Search.searchResults; if ($scope.searchResults.length < 1) { $scope.noResult = true; } else { $scope.noResult = false; } // Autocomplete $scope.location = ''; $scope.options2 = { country: 'ng' }; $scope.details2 = ''; //Date picker $scope.today = function() { $scope.dt = new Date(); var curr_date = $scope.dt.getDate(); var curr_month = $scope.dt.getMonth(); var curr_year = $scope.dt.getFullYear(); $scope.dt = curr_year + curr_month + curr_date; }; $scope.today(); $scope.clear = function() { $scope.dt = null; }; // Disable weekend selection $scope.disabled = function(date, mode) { return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6)); }; $scope.toggleMin = function() { $scope.minDate = $scope.minDate ? null : new Date(); }; $scope.toggleMin(); $scope.open = function($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']; $scope.format = $scope.formats[1]; $scope.stringFiles = []; //Image Upload $scope.onFileSelect = function($file) { $scope.select = $file; if ($scope.select[0].type === 'image/gif' || $scope.select[0].type === 'image/png' || $scope.select[0].type === 'image/jpg' || $scope.select[0].type === 'image/jpeg') { var reader = new FileReader(); reader.onload = function(e) { $scope.stringFiles.push({ path: e.target.result }); }; reader.readAsDataURL($scope.select[0]); } }; // Create new Program object $scope.create = function() { var program = new Programs({ category: this.category, name: this.name, location: this.location, programDate: this.programDate, description: this.description }); program.image = $scope.stringFiles; // Redirect after save program.$save(function(response) { $location.path('programs/' + response._id); // Clear form fields $scope.name = ''; $scope.location = ''; $scope.description = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Program $scope.remove = function(program) { if (program) { program.$remove(); for (var i in $scope.programs) { if ($scope.programs[i] === program) { $scope.programs.splice(i, 1); } } } else { $scope.program.$remove(function() { $location.path('programs'); }); } }; // Update existing Program $scope.update = function() { var program = $scope.program; program.$update(function() { $location.path('programs/' + program._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Programs $scope.find = function() { $scope.programs = Programs.query().sort(); }; function fixDate(i) { i = i.toString(); return i.length === 1 ? '0' + i : i; } //Find existing Program $scope.findOne = function() { $scope.programContent = Programs.get({ programId: $stateParams.programId }, function(response) { $scope.qrcodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=350x350&data='; // Setting Map Position try{ geocoder = new google.maps.Geocoder(); var options = { zoom: 17 }; var map = new google.maps.Map(document.getElementById('map_canvas'), options); var sAddress = $scope.programContent.program.location; geocoder.geocode({ 'address': sAddress }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { $scope.marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.BOUNCE }); map.setCenter(results[0].geometry.location); } }); } catch(e0) { } $scope.program = $scope.programContent.program; //Formating Date var cdate = new Date($scope.program.programDate); cdate = cdate.getFullYear() + '-' + fixDate(cdate.getMonth() + 1) + '-' + fixDate(cdate.getDate()); //Setting QR Code var qrData = encodeURIComponent('Title: ' + $scope.program.name + '\nDescription: ' + $scope.program.description + '\nDate: ' + cdate + '\nLocation: ' + $scope.program.location); $scope.qrcodeUrl = $scope.qrcodeUrl + qrData; delete $scope.programContent.program; delete $scope.programContent.userlike; for (var i in $scope.programContent) { $scope.program[i] = $scope.programContent[i]; } //Check if user has liked Event before $scope.hasLiked = $scope.programContent.userlike ? true : false; }); //Get Program Comments $scope.comments = ProgramsComment.query({ programId: $stateParams.programId }); }; $scope.addComments = function() { // Create new Comment object var comment = new ProgramsComment({ comment: $scope.newComment }); //Redirect after save comment.$save({ programId: $stateParams.programId }, function(response) { $scope.findOne(); $scope.newComment = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.doLike = function() { // Create new Like object var likeObject = { like: true }; var like = new ProgramsLike(likeObject); //Redirect after save like.$save({ programId: $stateParams.programId }, function(response) { $scope.hasLiked = response; if (response) { if (response.like) { $scope.program.likes.push(response._id); } else { var i = $scope.program.likes.indexOf(response._id); if (i > -1) { $scope.program.likes.splice(i, 1); $scope.hasLiked = false; } } } }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; } ]);
andela-tkomolafe/naijabuzz
public/modules/programs/controllers/programs.client.controller.js
JavaScript
mit
8,607
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc.5-master-3a0f323 */ goog.provide('ngmaterial.components.icon'); goog.require('ngmaterial.core'); /** * @ngdoc module * @name material.components.icon * @description * Icon */ angular.module('material.components.icon', ['material.core']); angular .module('material.components.icon') .directive('mdIcon', ['$mdIcon', '$mdTheming', '$mdAria', '$sce', mdIconDirective]); /** * @ngdoc directive * @name mdIcon * @module material.components.icon * * @restrict E * * @description * The `md-icon` directive makes it easier to use vector-based icons in your app (as opposed to * raster-based icons types like PNG). The directive supports both icon fonts and SVG icons. * * Icons should be consider view-only elements that should not be used directly as buttons; instead nest a `<md-icon>` * inside a `md-button` to add hover and click features. * * ### Icon fonts * Icon fonts are a technique in which you use a font where the glyphs in the font are * your icons instead of text. Benefits include a straightforward way to bundle everything into a * single HTTP request, simple scaling, easy color changing, and more. * * `md-icon` lets you consume an icon font by letting you reference specific icons in that font * by name rather than character code. * * ### SVG * For SVGs, the problem with using `<img>` or a CSS `background-image` is that you can't take * advantage of some SVG features, such as styling specific parts of the icon with CSS or SVG * animation. * * `md-icon` makes it easier to use SVG icons by *inlining* the SVG into an `<svg>` element in the * document. The most straightforward way of referencing an SVG icon is via URL, just like a * traditional `<img>`. `$mdIconProvider`, as a convenience, lets you _name_ an icon so you can * reference it by name instead of URL throughout your templates. * * Additionally, you may not want to make separate HTTP requests for every icon, so you can bundle * your SVG icons together and pre-load them with $mdIconProvider as an icon set. An icon set can * also be given a name, which acts as a namespace for individual icons, so you can reference them * like `"social:cake"`. * * When using SVGs, both external SVGs (via URLs) or sets of SVGs [from icon sets] can be * easily loaded and used.When use font-icons, developers must following three (3) simple steps: * * <ol> * <li>Load the font library. e.g.<br/> * `<link href="https://fonts.googleapis.com/icon?family=Material+Icons" * rel="stylesheet">` * </li> * <li> * Use either (a) font-icon class names or (b) font ligatures to render the font glyph by using * its textual name * </li> * <li> * Use `<md-icon md-font-icon="classname" />` or <br/> * use `<md-icon md-font-set="font library classname or alias"> textual_name </md-icon>` or <br/> * use `<md-icon md-font-set="font library classname or alias"> numerical_character_reference </md-icon>` * </li> * </ol> * * Full details for these steps can be found: * * <ul> * <li>http://google.github.io/material-design-icons/</li> * <li>http://google.github.io/material-design-icons/#icon-font-for-the-web</li> * </ul> * * The Material Design icon style <code>.material-icons</code> and the icon font references are published in * Material Design Icons: * * <ul> * <li>http://www.google.com/design/icons/</li> * <li>https://www.google.com/design/icons/#ic_accessibility</li> * </ul> * * <h2 id="material_design_icons">Material Design Icons</h2> * Using the Material Design Icon-Selector, developers can easily and quickly search for a Material Design font-icon and * determine its textual name and character reference code. Click on any icon to see the slide-up information * panel with details regarding a SVG download or information on the font-icon usage. * * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank" style="border-bottom:none;"> * <img src="https://cloud.githubusercontent.com/assets/210413/7902490/fe8dd14c-0780-11e5-98fb-c821cc6475e6.png" * aria-label="Material Design Icon-Selector" style="max-width:75%;padding-left:10%"> * </a> * * <span class="image_caption"> * Click on the image above to link to the * <a href="https://www.google.com/design/icons/#ic_accessibility" target="_blank">Material Design Icon-Selector</a>. * </span> * * @param {string} md-font-icon String name of CSS icon associated with the font-face will be used * to render the icon. Requires the fonts and the named CSS styles to be preloaded. * @param {string} md-font-set CSS style name associated with the font library; which will be assigned as * the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname; * internally use `$mdIconProvider.fontSet(<alias>)` to determine the style name. * @param {string} md-svg-src String URL (or expression) used to load, cache, and display an * external SVG. * @param {string} md-svg-icon md-svg-icon String name used for lookup of the icon from the internal cache; * interpolated strings or expressions may also be used. Specific set names can be used with * the syntax `<set name>:<icon name>`.<br/><br/> * To use icon sets, developers are required to pre-register the sets using the `$mdIconProvider` service. * @param {string=} aria-label Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no aria-label on the icon * nor a label on the parent element, a warning will be logged to the console. * @param {string=} alt Labels icon for accessibility. If an empty string is provided, icon * will be hidden from accessibility layer with `aria-hidden="true"`. If there's no alt on the icon * nor a label on the parent element, a warning will be logged to the console. * * @usage * When using SVGs: * <hljs lang="html"> * * <!-- Icon ID; may contain optional icon set prefix; icons must registered using $mdIconProvider --> * <md-icon md-svg-icon="social:android" aria-label="android " ></md-icon> * * <!-- Icon urls; may be preloaded in templateCache --> * <md-icon md-svg-src="/android.svg" aria-label="android " ></md-icon> * <md-icon md-svg-src="{{ getAndroid() }}" aria-label="android " ></md-icon> * * </hljs> * * Use the <code>$mdIconProvider</code> to configure your application with * svg iconsets. * * <hljs lang="js"> * angular.module('appSvgIconSets', ['ngMaterial']) * .controller('DemoCtrl', function($scope) {}) * .config(function($mdIconProvider) { * $mdIconProvider * .iconSet('social', 'img/icons/sets/social-icons.svg', 24) * .defaultIconSet('img/icons/sets/core-icons.svg', 24); * }); * </hljs> * * * When using Font Icons with classnames: * <hljs lang="html"> * * <md-icon md-font-icon="android" aria-label="android" ></md-icon> * <md-icon class="icon_home" aria-label="Home" ></md-icon> * * </hljs> * * When using Material Font Icons with ligatures: * <hljs lang="html"> * <!-- * For Material Design Icons * The class '.material-icons' is auto-added if a style has NOT been specified * since `material-icons` is the default fontset. So your markup: * --> * <md-icon> face </md-icon> * <!-- becomes this at runtime: --> * <md-icon md-font-set="material-icons"> face </md-icon> * <!-- If the fontset does not support ligature names, then we need to use the ligature unicode.--> * <md-icon> &#xE87C; </md-icon> * <!-- The class '.material-icons' must be manually added if other styles are also specified--> * <md-icon class="material-icons md-light md-48"> face </md-icon> * </hljs> * * When using other Font-Icon libraries: * * <hljs lang="js"> * // Specify a font-icon style alias * angular.config(function($mdIconProvider) { * $mdIconProvider.fontSet('md', 'material-icons'); * }); * </hljs> * * <hljs lang="html"> * <md-icon md-font-set="md">favorite</md-icon> * </hljs> * */ function mdIconDirective($mdIcon, $mdTheming, $mdAria, $sce) { return { restrict: 'E', link : postLink }; /** * Directive postLink * Supports embedded SVGs, font-icons, & external SVGs */ function postLink(scope, element, attr) { $mdTheming(element); var lastFontIcon = attr.mdFontIcon; var lastFontSet = $mdIcon.fontSet(attr.mdFontSet); prepareForFontIcon(); attr.$observe('mdFontIcon', fontIconChanged); attr.$observe('mdFontSet', fontIconChanged); // Keep track of the content of the svg src so we can compare against it later to see if the // attribute is static (and thus safe). var originalSvgSrc = element[0].getAttribute(attr.$attr.mdSvgSrc); // If using a font-icon, then the textual name of the icon itself // provides the aria-label. var label = attr.alt || attr.mdFontIcon || attr.mdSvgIcon || element.text(); var attrName = attr.$normalize(attr.$attr.mdSvgIcon || attr.$attr.mdSvgSrc || ''); if ( !attr['aria-label'] ) { if (label !== '' && !parentsHaveText() ) { $mdAria.expect(element, 'aria-label', label); $mdAria.expect(element, 'role', 'img'); } else if ( !element.text() ) { // If not a font-icon with ligature, then // hide from the accessibility layer. $mdAria.expect(element, 'aria-hidden', 'true'); } } if (attrName) { // Use either pre-configured SVG or URL source, respectively. attr.$observe(attrName, function(attrVal) { // If using svg-src and the value is static (i.e., is exactly equal to the compile-time // `md-svg-src` value), then it is implicitly trusted. if (!isInlineSvg(attrVal) && attrVal === originalSvgSrc) { attrVal = $sce.trustAsUrl(attrVal); } element.empty(); if (attrVal) { $mdIcon(attrVal) .then(function(svg) { element.empty(); element.append(svg); }); } }); } function parentsHaveText() { var parent = element.parent(); if (parent.attr('aria-label') || parent.text()) { return true; } else if(parent.parent().attr('aria-label') || parent.parent().text()) { return true; } return false; } function prepareForFontIcon() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.addClass('md-font ' + attr.mdFontIcon); } element.addClass(lastFontSet); } } function fontIconChanged() { if (!attr.mdSvgIcon && !attr.mdSvgSrc) { if (attr.mdFontIcon) { element.removeClass(lastFontIcon); element.addClass(attr.mdFontIcon); lastFontIcon = attr.mdFontIcon; } var fontSet = $mdIcon.fontSet(attr.mdFontSet); if (lastFontSet !== fontSet) { element.removeClass(lastFontSet); element.addClass(fontSet); lastFontSet = fontSet; } } } } /** * Gets whether the given svg src is an inline ("data:" style) SVG. * @param {string} svgSrc The svg src. * @returns {boolean} Whether the src is an inline SVG. */ function isInlineSvg(svgSrc) { var dataUrlRegex = /^data:image\/svg\+xml[\s*;\w\-\=]*?(base64)?,(.*)$/i; return dataUrlRegex.test(svgSrc); } } angular .module('material.components.icon') .constant('$$mdSvgRegistry', { 'mdTabsArrow': 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgMjQgMjQiPjxnPjxwb2x5Z29uIHBvaW50cz0iMTUuNCw3LjQgMTQsNiA4LDEyIDE0LDE4IDE1LjQsMTYuNiAxMC44LDEyICIvPjwvZz48L3N2Zz4=', 'mdClose': 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgMjQgMjQiPjxnPjxwYXRoIGQ9Ik0xOSA2LjQxbC0xLjQxLTEuNDEtNS41OSA1LjU5LTUuNTktNS41OS0xLjQxIDEuNDEgNS41OSA1LjU5LTUuNTkgNS41OSAxLjQxIDEuNDEgNS41OS01LjU5IDUuNTkgNS41OSAxLjQxLTEuNDEtNS41OS01LjU5eiIvPjwvZz48L3N2Zz4=', 'mdCancel': 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgMjQgMjQiPjxnPjxwYXRoIGQ9Ik0xMiAyYy01LjUzIDAtMTAgNC40Ny0xMCAxMHM0LjQ3IDEwIDEwIDEwIDEwLTQuNDcgMTAtMTAtNC40Ny0xMC0xMC0xMHptNSAxMy41OWwtMS40MSAxLjQxLTMuNTktMy41OS0zLjU5IDMuNTktMS40MS0xLjQxIDMuNTktMy41OS0zLjU5LTMuNTkgMS40MS0xLjQxIDMuNTkgMy41OSAzLjU5LTMuNTkgMS40MSAxLjQxLTMuNTkgMy41OSAzLjU5IDMuNTl6Ii8+PC9nPjwvc3ZnPg==', 'mdMenu': 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgMjQgMjQiPjxwYXRoIGQ9Ik0zLDZIMjFWOEgzVjZNMywxMUgyMVYxM0gzVjExTTMsMTZIMjFWMThIM1YxNloiIC8+PC9zdmc+', 'mdToggleArrow': 'data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHg9IjBweCIgeT0iMHB4IiB2aWV3Qm94PSIwIDAgNDggNDgiPjxwYXRoIGQ9Ik0yNCAxNmwtMTIgMTIgMi44MyAyLjgzIDkuMTctOS4xNyA5LjE3IDkuMTcgMi44My0yLjgzeiIvPjxwYXRoIGQ9Ik0wIDBoNDh2NDhoLTQ4eiIgZmlsbD0ibm9uZSIvPjwvc3ZnPg==', 'mdCalendar': 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTkgM2gtMVYxaC0ydjJIOFYxSDZ2Mkg1Yy0xLjExIDAtMS45OS45LTEuOTkgMkwzIDE5YzAgMS4xLjg5IDIgMiAyaDE0YzEuMSAwIDItLjkgMi0yVjVjMC0xLjEtLjktMi0yLTJ6bTAgMTZINVY4aDE0djExek03IDEwaDV2NUg3eiIvPjwvc3ZnPg==' }) .provider('$mdIcon', MdIconProvider); /** * @ngdoc service * @name $mdIconProvider * @module material.components.icon * * @description * `$mdIconProvider` is used only to register icon IDs with URLs. These configuration features allow * icons and icon sets to be pre-registered and associated with source URLs **before** the `<md-icon />` * directives are compiled. * * If using font-icons, the developer is responsible for loading the fonts. * * If using SVGs, loading of the actual svg files are deferred to on-demand requests and are loaded * internally by the `$mdIcon` service using the `$templateRequest` service. When an SVG is * requested by name/ID, the `$mdIcon` service searches its registry for the associated source URL; * that URL is used to on-demand load and parse the SVG dynamically. * * The `$templateRequest` service expects the icons source to be loaded over trusted URLs.<br/> * This means, when loading icons from an external URL, you have to trust the URL in the `$sceDelegateProvider`. * * <hljs lang="js"> * app.config(function($sceDelegateProvider) { * $sceDelegateProvider.resourceUrlWhitelist([ * // Adding 'self' to the whitelist, will allow requests from the current origin. * 'self', * // Using double asterisks here, will allow all URLs to load. * // We recommend to only specify the given domain you want to allow. * '**' * ]); * }); * </hljs> * * Read more about the [$sceDelegateProvider](https://docs.angularjs.org/api/ng/provider/$sceDelegateProvider). * * **Notice:** Most font-icons libraries do not support ligatures (for example `fontawesome`).<br/> * In such cases you are not able to use the icon's ligature name - Like so: * * <hljs lang="html"> * <md-icon md-font-set="fa">fa-bell</md-icon> * </hljs> * * You should instead use the given unicode, instead of the ligature name. * * <p ng-hide="true"> ##// Notice we can't use a hljs element here, because the characters will be escaped.</p> * ```html * <md-icon md-font-set="fa">&#xf0f3</md-icon> * ``` * * All unicode ligatures are prefixed with the `&#x` string. * * @usage * <hljs lang="js"> * app.config(function($mdIconProvider) { * * // Configure URLs for icons specified by [set:]id. * * $mdIconProvider * .defaultFontSet( 'fa' ) // This sets our default fontset className. * .defaultIconSet('my/app/icons.svg') // Register a default set of SVG icons * .iconSet('social', 'my/app/social.svg') // Register a named icon set of SVGs * .icon('android', 'my/app/android.svg') // Register a specific icon (by name) * .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set * }); * </hljs> * * SVG icons and icon sets can be easily pre-loaded and cached using either (a) a build process or (b) a runtime * **startup** process (shown below): * * <hljs lang="js"> * app.config(function($mdIconProvider) { * * // Register a default set of SVG icon definitions * $mdIconProvider.defaultIconSet('my/app/icons.svg') * * }) * .run(function($templateRequest){ * * // Pre-fetch icons sources by URL and cache in the $templateCache... * // subsequent $templateRequest calls will look there first. * * var urls = [ 'imy/app/icons.svg', 'img/icons/android.svg']; * * angular.forEach(urls, function(url) { * $templateRequest(url); * }); * * }); * * </hljs> * * NOTE: the loaded SVG data is subsequently cached internally for future requests. * */ /** * @ngdoc method * @name $mdIconProvider#icon * * @description * Register a source URL for a specific icon name; the name may include optional 'icon set' name prefix. * These icons will later be retrieved from the cache using `$mdIcon( <icon name> )` * * @param {string} id Icon name/id used to register the icon * @param {string} url specifies the external location for the data file. Used internally by * `$templateRequest` to load the data or as part of the lookup in `$templateCache` if pre-loading * was configured. * @param {number=} viewBoxSize Sets the width and height the icon's viewBox. * It is ignored for icons with an existing viewBox. Default size is 24. * * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API * * @usage * <hljs lang="js"> * app.config(function($mdIconProvider) { * * // Configure URLs for icons specified by [set:]id. * * $mdIconProvider * .icon('android', 'my/app/android.svg') // Register a specific icon (by name) * .icon('work:chair', 'my/app/chair.svg'); // Register icon in a specific set * }); * </hljs> * */ /** * @ngdoc method * @name $mdIconProvider#iconSet * * @description * Register a source URL for a 'named' set of icons; group of SVG definitions where each definition * has an icon id. Individual icons can be subsequently retrieved from this cached set using * `$mdIcon(<icon set name>:<icon name>)` * * @param {string} id Icon name/id used to register the iconset * @param {string} url specifies the external location for the data file. Used internally by * `$templateRequest` to load the data or as part of the lookup in `$templateCache` if pre-loading * was configured. * @param {number=} viewBoxSize Sets the width and height of the viewBox of all icons in the set. * It is ignored for icons with an existing viewBox. All icons in the icon set should be the same size. * Default value is 24. * * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API * * * @usage * <hljs lang="js"> * app.config(function($mdIconProvider) { * * // Configure URLs for icons specified by [set:]id. * * $mdIconProvider * .iconSet('social', 'my/app/social.svg') // Register a named icon set * }); * </hljs> * */ /** * @ngdoc method * @name $mdIconProvider#defaultIconSet * * @description * Register a source URL for the default 'named' set of icons. Unless explicitly registered, * subsequent lookups of icons will failover to search this 'default' icon set. * Icon can be retrieved from this cached, default set using `$mdIcon(<name>)` * * @param {string} url specifies the external location for the data file. Used internally by * `$templateRequest` to load the data or as part of the lookup in `$templateCache` if pre-loading * was configured. * @param {number=} viewBoxSize Sets the width and height of the viewBox of all icons in the set. * It is ignored for icons with an existing viewBox. All icons in the icon set should be the same size. * Default value is 24. * * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API * * @usage * <hljs lang="js"> * app.config(function($mdIconProvider) { * * // Configure URLs for icons specified by [set:]id. * * $mdIconProvider * .defaultIconSet( 'my/app/social.svg' ) // Register a default icon set * }); * </hljs> * */ /** * @ngdoc method * @name $mdIconProvider#defaultFontSet * * @description * When using Font-Icons, Angular Material assumes the the Material Design icons will be used and automatically * configures the default font-set == 'material-icons'. Note that the font-set references the font-icon library * class style that should be applied to the `<md-icon>`. * * Configuring the default means that the attributes * `md-font-set="material-icons"` or `class="material-icons"` do not need to be explicitly declared on the * `<md-icon>` markup. For example: * * `<md-icon> face </md-icon>` * will render as * `<span class="material-icons"> face </span>`, and * * `<md-icon md-font-set="fa"> face </md-icon>` * will render as * `<span class="fa"> face </span>` * * @param {string} name of the font-library style that should be applied to the md-icon DOM element * * @usage * <hljs lang="js"> * app.config(function($mdIconProvider) { * $mdIconProvider.defaultFontSet( 'fa' ); * }); * </hljs> * */ /** * @ngdoc method * @name $mdIconProvider#fontSet * * @description * When using a font set for `<md-icon>` you must specify the correct font classname in the `md-font-set` * attribute. If the fonset className is really long, your markup may become cluttered... an easy * solution is to define an `alias` for your fontset: * * @param {string} alias of the specified fontset. * @param {string} className of the fontset. * * @usage * <hljs lang="js"> * app.config(function($mdIconProvider) { * // In this case, we set an alias for the `material-icons` fontset. * $mdIconProvider.fontSet('md', 'material-icons'); * }); * </hljs> * */ /** * @ngdoc method * @name $mdIconProvider#defaultViewBoxSize * * @description * While `<md-icon />` markup can also be style with sizing CSS, this method configures * the default width **and** height used for all icons; unless overridden by specific CSS. * The default sizing is (24px, 24px). * @param {number=} viewBoxSize Sets the width and height of the viewBox for an icon or an icon set. * All icons in a set should be the same size. The default value is 24. * * @returns {obj} an `$mdIconProvider` reference; used to support method call chains for the API * * @usage * <hljs lang="js"> * app.config(function($mdIconProvider) { * * // Configure URLs for icons specified by [set:]id. * * $mdIconProvider * .defaultViewBoxSize(36) // Register a default icon size (width == height) * }); * </hljs> * */ var config = { defaultViewBoxSize: 24, defaultFontSet: 'material-icons', fontSets: [] }; function MdIconProvider() { } MdIconProvider.prototype = { icon: function(id, url, viewBoxSize) { if (id.indexOf(':') == -1) id = '$default:' + id; config[id] = new ConfigurationItem(url, viewBoxSize); return this; }, iconSet: function(id, url, viewBoxSize) { config[id] = new ConfigurationItem(url, viewBoxSize); return this; }, defaultIconSet: function(url, viewBoxSize) { var setName = '$default'; if (!config[setName]) { config[setName] = new ConfigurationItem(url, viewBoxSize); } config[setName].viewBoxSize = viewBoxSize || config.defaultViewBoxSize; return this; }, defaultViewBoxSize: function(viewBoxSize) { config.defaultViewBoxSize = viewBoxSize; return this; }, /** * Register an alias name associated with a font-icon library style ; */ fontSet: function fontSet(alias, className) { config.fontSets.push({ alias: alias, fontSet: className || alias }); return this; }, /** * Specify a default style name associated with a font-icon library * fallback to Material Icons. * */ defaultFontSet: function defaultFontSet(className) { config.defaultFontSet = !className ? '' : className; return this; }, defaultIconSize: function defaultIconSize(iconSize) { config.defaultIconSize = iconSize; return this; }, $get: ['$templateRequest', '$q', '$log', '$mdUtil', '$sce', function($templateRequest, $q, $log, $mdUtil, $sce) { return MdIconService(config, $templateRequest, $q, $log, $mdUtil, $sce); }] }; /** * Configuration item stored in the Icon registry; used for lookups * to load if not already cached in the `loaded` cache */ function ConfigurationItem(url, viewBoxSize) { this.url = url; this.viewBoxSize = viewBoxSize || config.defaultViewBoxSize; } /** * @ngdoc service * @name $mdIcon * @module material.components.icon * * @description * The `$mdIcon` service is a function used to lookup SVG icons. * * @param {string} id Query value for a unique Id or URL. If the argument is a URL, then the service will retrieve the icon element * from its internal cache or load the icon and cache it first. If the value is not a URL-type string, then an ID lookup is * performed. The Id may be a unique icon ID or may include an iconSet ID prefix. * * For the **id** query to work properly, this means that all id-to-URL mappings must have been previously configured * using the `$mdIconProvider`. * * @returns {angular.$q.Promise} A promise that gets resolved to a clone of the initial SVG DOM element; which was * created from the SVG markup in the SVG data file. If an error occurs (e.g. the icon cannot be found) the promise * will get rejected. * * @usage * <hljs lang="js"> * function SomeDirective($mdIcon) { * * // See if the icon has already been loaded, if not * // then lookup the icon from the registry cache, load and cache * // it for future requests. * // NOTE: ID queries require configuration with $mdIconProvider * * $mdIcon('android').then(function(iconEl) { element.append(iconEl); }); * $mdIcon('work:chair').then(function(iconEl) { element.append(iconEl); }); * * // Load and cache the external SVG using a URL * * $mdIcon('img/icons/android.svg').then(function(iconEl) { * element.append(iconEl); * }); * }; * </hljs> * * NOTE: The `<md-icon /> ` directive internally uses the `$mdIcon` service to query, loaded, and instantiate * SVG DOM elements. */ /* ngInject */ function MdIconService(config, $templateRequest, $q, $log, $mdUtil, $sce) { var iconCache = {}; var svgCache = {}; var urlRegex = /[-\w@:%\+.~#?&//=]{2,}\.[a-z]{2,4}\b(\/[-\w@:%\+.~#?&//=]*)?/i; var dataUrlRegex = /^data:image\/svg\+xml[\s*;\w\-\=]*?(base64)?,(.*)$/i; Icon.prototype = {clone: cloneSVG, prepare: prepareAndStyle}; getIcon.fontSet = findRegisteredFontSet; // Publish service... return getIcon; /** * Actual $mdIcon service is essentially a lookup function */ function getIcon(id) { id = id || ''; // If the "id" provided is not a string, the only other valid value is a $sce trust wrapper // over a URL string. If the value is not trusted, this will intentionally throw an error // because the user is attempted to use an unsafe URL, potentially opening themselves up // to an XSS attack. if (!angular.isString(id)) { id = $sce.getTrustedUrl(id); } // If already loaded and cached, use a clone of the cached icon. // Otherwise either load by URL, or lookup in the registry and then load by URL, and cache. if (iconCache[id]) { return $q.when(transformClone(iconCache[id])); } if (urlRegex.test(id) || dataUrlRegex.test(id)) { return loadByURL(id).then(cacheIcon(id)); } if (id.indexOf(':') == -1) { id = '$default:' + id; } var load = config[id] ? loadByID : loadFromIconSet; return load(id) .then(cacheIcon(id)); } /** * Lookup registered fontSet style using its alias... * If not found, */ function findRegisteredFontSet(alias) { var useDefault = angular.isUndefined(alias) || !(alias && alias.length); if (useDefault) return config.defaultFontSet; var result = alias; angular.forEach(config.fontSets, function(it) { if (it.alias == alias) result = it.fontSet || result; }); return result; } function transformClone(cacheElement) { var clone = cacheElement.clone(); var cacheSuffix = '_cache' + $mdUtil.nextUid(); // We need to modify for each cached icon the id attributes. // This is needed because SVG id's are treated as normal DOM ids // and should not have a duplicated id. if (clone.id) clone.id += cacheSuffix; angular.forEach(clone.querySelectorAll('[id]'), function(item) { item.id += cacheSuffix; }); return clone; } /** * Prepare and cache the loaded icon for the specified `id` */ function cacheIcon(id) { return function updateCache(icon) { iconCache[id] = isIcon(icon) ? icon : new Icon(icon, config[id]); return iconCache[id].clone(); }; } /** * Lookup the configuration in the registry, if !registered throw an error * otherwise load the icon [on-demand] using the registered URL. * */ function loadByID(id) { var iconConfig = config[id]; return loadByURL(iconConfig.url).then(function(icon) { return new Icon(icon, iconConfig); }); } /** * Loads the file as XML and uses querySelector( <id> ) to find * the desired node... */ function loadFromIconSet(id) { var setName = id.substring(0, id.lastIndexOf(':')) || '$default'; var iconSetConfig = config[setName]; return !iconSetConfig ? announceIdNotFound(id) : loadByURL(iconSetConfig.url).then(extractFromSet); function extractFromSet(set) { var iconName = id.slice(id.lastIndexOf(':') + 1); var icon = set.querySelector('#' + iconName); return icon ? new Icon(icon, iconSetConfig) : announceIdNotFound(id); } function announceIdNotFound(id) { var msg = 'icon ' + id + ' not found'; $log.warn(msg); return $q.reject(msg || id); } } /** * Load the icon by URL (may use the $templateCache). * Extract the data for later conversion to Icon */ function loadByURL(url) { /* Load the icon from embedded data URL. */ function loadByDataUrl(url) { var results = dataUrlRegex.exec(url); var isBase64 = /base64/i.test(url); var data = isBase64 ? window.atob(results[2]) : results[2]; return $q.when(angular.element(data)[0]); } /* Load the icon by URL using HTTP. */ function loadByHttpUrl(url) { return $q(function(resolve, reject) { // Catch HTTP or generic errors not related to incorrect icon IDs. var announceAndReject = function(err) { var msg = angular.isString(err) ? err : (err.message || err.data || err.statusText); $log.warn(msg); reject(err); }, extractSvg = function(response) { if (!svgCache[url]) { svgCache[url] = angular.element('<div>').append(response)[0].querySelector('svg'); } resolve(svgCache[url]); }; $templateRequest(url, true).then(extractSvg, announceAndReject); }); } return dataUrlRegex.test(url) ? loadByDataUrl(url) : loadByHttpUrl(url); } /** * Check target signature to see if it is an Icon instance. */ function isIcon(target) { return angular.isDefined(target.element) && angular.isDefined(target.config); } /** * Define the Icon class */ function Icon(el, config) { if (el && el.tagName != 'svg') { el = angular.element('<svg xmlns="http://www.w3.org/2000/svg">').append(el.cloneNode(true))[0]; } // Inject the namespace if not available... if (!el.getAttribute('xmlns')) { el.setAttribute('xmlns', "http://www.w3.org/2000/svg"); } this.element = el; this.config = config; this.prepare(); } /** * Prepare the DOM element that will be cached in the * loaded iconCache store. */ function prepareAndStyle() { var viewBoxSize = this.config ? this.config.viewBoxSize : config.defaultViewBoxSize; angular.forEach({ 'fit': '', 'height': '100%', 'width': '100%', 'preserveAspectRatio': 'xMidYMid meet', 'viewBox': this.element.getAttribute('viewBox') || ('0 0 ' + viewBoxSize + ' ' + viewBoxSize), 'focusable': false // Disable IE11s default behavior to make SVGs focusable }, function(val, attr) { this.element.setAttribute(attr, val); }, this); } /** * Clone the Icon DOM element. */ function cloneSVG() { // If the element or any of its children have a style attribute, then a CSP policy without // 'unsafe-inline' in the style-src directive, will result in a violation. return this.element.cloneNode(true); } } MdIconService.$inject = ["config", "$templateRequest", "$q", "$log", "$mdUtil", "$sce"]; ngmaterial.components.icon = angular.module("material.components.icon");
rebeccaForster/ThinkTank
Iteration5_Prototype/v1/node_modules/angular-material/modules/closure/icon/icon.js
JavaScript
mit
33,632
(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['snd.TimeLineEvent', 'snd.TimeValue'], factory); } else if (typeof exports === 'object') { // Node } else { // Browser globals (root is window) root.snd = factory(root.snd); } }(this, function(snd) { snd.Envelope = function(id, target) { snd.TimeLineEvent.call(this, id, target, 0, Infinity); this._timeValueChangeEventListeners = []; this._timeValueAddEventListeners = []; this._timeValueRemoveEventListeners = []; Object.defineProperties(this, { length: { get: function() { return this._envelope.length; } } }); // {time: t, value: v} this._envelope = []; }; snd.Envelope.prototype = Object.create(snd.TimeLineEvent.prototype); snd.Envelope.prototype.constructor = snd.Envelope; snd.Envelope.prototype.start = function(time, currentTime) { if (this._target && this._status != snd.status.STARTED) { var _this = this; var diff = this.startTime - time; var when = (diff < 0) ? 0 : diff; var offset = (diff < 0) ? Math.abs(diff) : 0; var duration = this.endTime - this.startTime - offset; this.setEnvelope(when, offset, duration, (currentTime == null) ? snd.CURRENT_TIME : currentTime); this._status = snd.status.STARTED; if (typeof(this.target.addOnEndedEventListener) == "function") { this.target.addOnEndedEventListener(this.receiveOnEndedEvent); } else { this._timerID = setTimeout((function(thisarg){thisarg.status = snd.status.READY;})(_this), duration); } this.fireStartEvent(); } }; snd.Envelope.prototype.get = function(i) { return this._envelope[i]; }; snd.Envelope.prototype.push = function(timeValueObj) { var _this = this; timeValueObj.addTimeValueChangeEventListener(function(tv,pt,pv){_this.receiveTimeValueChangeEvent(tv,pt,pv);}); this._envelope.push(timeValueObj); this._envelope.sort(snd.Envelope.compareTimeValueArray); this.fireTimeValueAddEvent(this, timeValueObj); }; snd.Envelope.prototype.indexOf = function(timeValueObj) { return this._envelope.indexOf(timeValueObj); }; snd.Envelope.prototype.remove = function(timeValueObj) { var i = this._envelope.indexOf(timeValueObj); if (i >= 0) { this.splice(i, 1); } }; snd.Envelope.prototype.splice = function(i, n) { if (i > 0) { var timeValueObj = this._envelope[i]; timeValueObj.removeTimeValueChangeEventListener(this.receiveTimeValueChangeEvent); this._envelope.splice(i, n); this.fireTimeValueRemoveEvent(this, timeValueObj); } }; snd.Envelope.prototype.onTimeValueChanged = function(obj, timeValueObj) {}; snd.Envelope.prototype.onTimeValueAdded = function(obj, timeValueObj) {}; snd.Envelope.prototype.onTimeValueRemoved = function(obj, timeValueObj) {}; snd.Envelope.prototype.addTimeValueAddEventListener = function(listener) { this._timeValueAddEventListeners.push(listener); }; snd.Envelope.prototype.removeTimeValueAddEventListener = function(listener) { var i = this._timeValueAddEventListeners.indexOf(listener); if (i >= 0) { this._timeValueAddEventListeners.splice(i, 1); } }; snd.Envelope.prototype.addTimeValueChangeEventListener = function(listener) { this._timeValueChangeEventListeners.push(listener); }; snd.Envelope.prototype.removeTimeValueChangeEventListener = function(listener) { var i = this._timeValueChangeEventListeners.indexOf(listener); if (i >= 0) { this._timeValueChangeEventListeners.splice(i, 1); } }; snd.Envelope.prototype.addTimeValueRemoveEventListener = function(listener) { this._timeValueRemoveEventListeners.push(listener); }; snd.Envelope.prototype.removeTimeValueRemoveEventListener = function(listener) { var i = this._timeValueRemoveEventListeners.indexOf(listener); if (i >= 0) { this._timeValueRemoveEventListeners.splice(i, 1); } }; snd.Envelope.prototype.fireTimeValueChangeEvent = function(obj, timeValueObj, prevTime, prevValue) { this.onTimeValueChanged(obj, timeValueObj, prevTime, prevValue); for (var i in this._timeValueChangeEventListeners) { if (typeof(this._timeValueChangeEventListeners[i]) == 'function') { this._timeValueChangeEventListeners[i](obj, timeValueObj); } } }; snd.Envelope.prototype.fireTimeValueAddEvent = function(obj, timeValueObj) { this.onTimeValueAdded(obj, timeValueObj); for (var i in this._timeValueAddEventListeners) { if (typeof(this._timeValueAddEventListeners[i]) == 'function') { this._timeValueAddEventListeners[i](obj, timeValueObj); } } }; snd.Envelope.prototype.fireTimeValueRemoveEvent = function(obj, timeValueObj) { this.onTimeValueRemoved(obj, timeValueObj); for (var i in this._timeValueRemoveEventListeners) { if (typeof(this._timeValueRemoveEventListeners[i]) == 'function') { this._timeValueRemoveEventListeners[i](obj, timeValueObj); } } }; snd.Envelope.prototype.receiveTimeValueChangeEvent = function(timeValueObj, prevTime, prevValue) { var idx = this._envelope.indexOf(timeValueObj); if (idx >= 0) { if ((idx - 1 > 0) && (this._envelope[idx].time < this._envelope[idx -1])) { this._envelope.sort(snd.Envelope.compareTimeValueArray); } else if ((idx + 1 < this._envelope.length) && (this._envelope[idx] > this._envelope[idx + 1])) { this._envelope.sort(snd.Envelope.compareTimeValueArray); } } this.fireTimeValueChangeEvent(this, timeValueObj, prevTime, prevValue); }; snd.Envelope.prototype.setEnvelope = function(when, offset, duration, currentTime) { if (this._envelope.length > 0) { var tv = this.calcSetTime(offset); this.setEnvelopeToTarget(currentTime, when, offset, tv.index, tv.left); } }; snd.Envelope.prototype.calcSetTime = function(time) { var i, left; if (time <= this._envelope[0].time) { i = 0; left = {time: time, value: this._envelope[0].value}; } else if (this._envelope[this._envelope.length - 1].time <= time) { i = this._envelope.length - 1; left = this._envelope[i]; } else { var l = null, r = null, nowTimeVal = null; for (i = 0; i < this._envelope.length; i++) { if (this._envelope[i].time == time) { nowTimeVal = this._envelope[i]; break; } else if (this._envelope[i].time > time) { l = this._envelope[i - 1]; r = this._envelope[i]; nowTimeVal = {time: time, value: l.value + (r.value - l.value) * (time - l.time) / (r.time - l.time)}; break; } } left = nowTimeVal; } return {index: i, left: left}; }; snd.Envelope.prototype.setEnvelopeToTarget = function(currentTime, when, offset, idx, left) { var startAt = currentTime + when; this._target.cancelScheduledValues(0); if (idx >= this._envelope.length) { // Envelope already finished. // Set last envelope value to target AudioParam and return this method. this._target.setValueAtTime(left.value, startAt); return; } // Set first envelope value to target AudioParam. this._target.setValueAtTime(left.value, startAt); for (var i = idx; i < this._envelope.length; i++) { var e = this._envelope[i]; this._target.linearRampToValueAtTime(e.value, startAt + e.time - offset); } }; snd.Envelope.compareTimeValueArray = function(a, b) { if (!a || !a.time) { return -1; } if (!b || !b.time) { return 1; } if (a.time < b.time) { return -1; } else if (a.time == b.time) { return 0; } else { return 1; } }; return snd; }));
h10x64/snd.js
src/class/optional/TimeLine/snd.Envelope.js
JavaScript
mit
8,752
import React from 'react/addons'; import {RouteStore, LinkTo} from 'fl-router'; import MailboxStore from '../stores/MailboxStore.js'; import MailboxRow from '../components/MailboxRow.js'; var PureRenderMixin = React.addons.PureRenderMixin; function getStateFromStores () { return { mailboxId: MailboxStore.getSelectedMailboxId(), mailboxes: MailboxStore.getMailboxes(), // Immutable.Map activeURL: RouteStore.getURL() }; } export default React.createClass({ displayName: 'MailboxesView', mixins: [PureRenderMixin], getInitialState: function () { return getStateFromStores(); }, componentWillMount: function () { MailboxStore.addChangeListener(this._onChange); }, componentWillUnmount: function () { MailboxStore.removeChangeListener(this._onChange); }, render: function () { var mailboxes; mailboxes = []; // be careful here, if using .map() you will result in // an immutable iterable that react does not natively support this.state.mailboxes.forEach(function (mailbox, mailboxId) { mailboxes.push( <li key={mailboxId}> <LinkTo route='mailbox' params={[mailboxId]} activeURL={this.state.activeURL}> <MailboxRow mailbox={mailbox} /> </LinkTo> </li> ); }.bind(this)); return ( <ul className='mailboxes'> {mailboxes} </ul> ); }, _onChange: function () { this.setState(getStateFromStores()); } });
danjamin/react-fluxlike-mail-demo
app/views/MailboxesView.js
JavaScript
mit
1,476
define([ 'libs/angular' ], function(angular) { 'use strict'; function ctrl($scope) { } return ctrl; });
erykpiast/appetite
public/controllers/footer.js
JavaScript
mit
117
import "ember"; import isEnabled from "ember-metal/features"; import { objectControllerDeprecation } from "ember-runtime/controllers/object_controller"; import EmberHandlebars from "ember-htmlbars/compat"; import EmberView from "ember-views/views/view"; var compile = EmberHandlebars.compile; var Router, App, AppView, router, registry, container; var set = Ember.set; function bootApplication() { router = container.lookup('router:main'); Ember.run(App, 'advanceReadiness'); } // IE includes the host name function normalizeUrl(url) { return url.replace(/https?:\/\/[^\/]+/, ''); } function shouldNotBeActive(selector) { checkActive(selector, false); } function shouldBeActive(selector) { checkActive(selector, true); } function checkActive(selector, active) { var classList = Ember.$(selector, '#qunit-fixture')[0].className; equal(classList.indexOf('active') > -1, active, selector + " active should be " + active.toString()); } var updateCount, replaceCount; function sharedSetup() { App = Ember.Application.create({ name: "App", rootElement: '#qunit-fixture' }); App.deferReadiness(); updateCount = replaceCount = 0; App.Router.reopen({ location: Ember.NoneLocation.createWithMixins({ setURL(path) { updateCount++; set(this, 'path', path); }, replaceURL(path) { replaceCount++; set(this, 'path', path); } }) }); Router = App.Router; registry = App.registry; container = App.__container__; } function sharedTeardown() { Ember.run(function() { App.destroy(); }); Ember.TEMPLATES = {}; } QUnit.module("The {{link-to}} helper", { setup() { Ember.run(function() { sharedSetup(); Ember.TEMPLATES.app = compile("{{outlet}}"); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'about' id='about-link'}}About{{/link-to}}{{#link-to 'index' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.about = compile("<h3>About</h3>{{#link-to 'index' id='home-link'}}Home{{/link-to}}{{#link-to 'about' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.item = compile("<h3>Item</h3><p>{{model.name}}</p>{{#link-to 'index' id='home-link'}}Home{{/link-to}}"); AppView = EmberView.extend({ templateName: 'app' }); registry.register('view:app', AppView); registry.unregister('router:main'); registry.register('router:main', Router); }); }, teardown: sharedTeardown }); QUnit.test("The {{link-to}} helper moves into the named route", function() { Router.map(function(match) { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('h3:contains(Home)', '#qunit-fixture').length, 1, "The home template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#about-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(About)', '#qunit-fixture').length, 1, "The about template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#home-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); }); QUnit.test("The {{link-to}} helper supports URL replacement", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'about' id='about-link' replace=true}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(updateCount, 0, 'precond: setURL has not been called'); equal(replaceCount, 0, 'precond: replaceURL has not been called'); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(updateCount, 0, 'setURL should not be called'); equal(replaceCount, 1, 'replaceURL should be called once'); }); QUnit.test("the {{link-to}} helper doesn't add an href when the tagName isn't 'a'", function() { Ember.TEMPLATES.index = compile("{{#link-to 'about' id='about-link' tagName='div'}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#about-link').attr('href'), undefined, "there is no href attribute"); }); QUnit.test("the {{link-to}} applies a 'disabled' class when disabled", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link" disabledWhen="shouldDisable"}}About{{/link-to}}'); App.IndexController = Ember.Controller.extend({ shouldDisable: true }); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#about-link.disabled', '#qunit-fixture').length, 1, "The link is disabled when its disabledWhen is true"); }); QUnit.test("the {{link-to}} doesn't apply a 'disabled' class if disabledWhen is not provided", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link"}}About{{/link-to}}'); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); ok(!Ember.$('#about-link', '#qunit-fixture').hasClass("disabled"), "The link is not disabled if disabledWhen not provided"); }); QUnit.test("the {{link-to}} helper supports a custom disabledClass", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link" disabledWhen=true disabledClass="do-not-want"}}About{{/link-to}}'); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#about-link.do-not-want', '#qunit-fixture').length, 1, "The link can apply a custom disabled class"); }); QUnit.test("the {{link-to}} helper does not respond to clicks when disabled", function () { Ember.TEMPLATES.index = compile('{{#link-to "about" id="about-link" disabledWhen=true}}About{{/link-to}}'); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(About)', '#qunit-fixture').length, 0, "Transitioning did not occur"); }); QUnit.test("The {{link-to}} helper supports a custom activeClass", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'about' id='about-link'}}About{{/link-to}}{{#link-to 'index' id='self-link' activeClass='zomg-active'}}Self{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('h3:contains(Home)', '#qunit-fixture').length, 1, "The home template was rendered"); equal(Ember.$('#self-link.zomg-active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#about-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); }); QUnit.test("The {{link-to}} helper supports leaving off .index for nested routes", function() { Router.map(function() { this.resource("about", function() { this.route("item"); }); }); Ember.TEMPLATES.about = compile("<h1>About</h1>{{outlet}}"); Ember.TEMPLATES['about/index'] = compile("<div id='index'>Index</div>"); Ember.TEMPLATES['about/item'] = compile("<div id='item'>{{#link-to 'about'}}About{{/link-to}}</div>"); bootApplication(); Ember.run(router, 'handleURL', '/about/item'); equal(normalizeUrl(Ember.$('#item a', '#qunit-fixture').attr('href')), '/about'); }); QUnit.test("The {{link-to}} helper supports currentWhen (DEPRECATED)", function() { expectDeprecation('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.'); Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.route("item"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'item' id='other-link' currentWhen='index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#other-link.active', '#qunit-fixture').length, 1, "The link is active since current-when is a parent route"); }); QUnit.test("The {{link-to}} helper supports custom, nested, current-when", function() { Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.route("item"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'item' id='other-link' current-when='index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#other-link.active', '#qunit-fixture').length, 1, "The link is active since current-when is a parent route"); }); QUnit.test("The {{link-to}} helper does not disregard current-when when it is given explicitly for a resource", function() { Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.resource("items", function() { this.route('item'); }); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'items' id='other-link' current-when='index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#other-link.active', '#qunit-fixture').length, 1, "The link is active when current-when is given for explicitly for a resource"); }); QUnit.test("The {{link-to}} helper supports multiple current-when routes", function() { Router.map(function(match) { this.resource("index", { path: "/" }, function() { this.route("about"); }); this.route("item"); this.route("foo"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{outlet}}"); Ember.TEMPLATES['index/about'] = compile("{{#link-to 'item' id='link1' current-when='item index'}}ITEM{{/link-to}}"); Ember.TEMPLATES['item'] = compile("{{#link-to 'item' id='link2' current-when='item index'}}ITEM{{/link-to}}"); Ember.TEMPLATES['foo'] = compile("{{#link-to 'item' id='link3' current-when='item index'}}ITEM{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('#link1.active', '#qunit-fixture').length, 1, "The link is active since current-when contains the parent route"); Ember.run(function() { router.handleURL("/item"); }); equal(Ember.$('#link2.active', '#qunit-fixture').length, 1, "The link is active since you are on the active route"); Ember.run(function() { router.handleURL("/foo"); }); equal(Ember.$('#link3.active', '#qunit-fixture').length, 0, "The link is not active since current-when does not contain the active route"); }); QUnit.test("The {{link-to}} helper defaults to bubbling", function() { Ember.TEMPLATES.about = compile("<div {{action 'hide'}}>{{#link-to 'about.contact' id='about-contact'}}About{{/link-to}}</div>{{outlet}}"); Ember.TEMPLATES['about/contact'] = compile("<h1 id='contact'>Contact</h1>"); Router.map(function() { this.resource("about", function() { this.route("contact"); }); }); var hidden = 0; App.AboutRoute = Ember.Route.extend({ actions: { hide() { hidden++; } } }); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); Ember.run(function() { Ember.$('#about-contact', '#qunit-fixture').click(); }); equal(Ember.$("#contact", "#qunit-fixture").text(), "Contact", "precond - the link worked"); equal(hidden, 1, "The link bubbles"); }); QUnit.test("The {{link-to}} helper supports bubbles=false", function() { Ember.TEMPLATES.about = compile("<div {{action 'hide'}}>{{#link-to 'about.contact' id='about-contact' bubbles=false}}About{{/link-to}}</div>{{outlet}}"); Ember.TEMPLATES['about/contact'] = compile("<h1 id='contact'>Contact</h1>"); Router.map(function() { this.resource("about", function() { this.route("contact"); }); }); var hidden = 0; App.AboutRoute = Ember.Route.extend({ actions: { hide() { hidden++; } } }); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); Ember.run(function() { Ember.$('#about-contact', '#qunit-fixture').click(); }); equal(Ember.$("#contact", "#qunit-fixture").text(), "Contact", "precond - the link worked"); equal(hidden, 0, "The link didn't bubble"); }); QUnit.test("The {{link-to}} helper moves into the named route with context", function() { Router.map(function(match) { this.route("about"); this.resource("item", { path: "/item/:id" }); }); Ember.TEMPLATES.about = compile("<h3>List</h3><ul>{{#each model as |person|}}<li>{{#link-to 'item' person}}{{person.name}}{{/link-to}}</li>{{/each}}</ul>{{#link-to 'index' id='home-link'}}Home{{/link-to}}"); App.AboutRoute = Ember.Route.extend({ model() { return Ember.A([ { id: "yehuda", name: "Yehuda Katz" }, { id: "tom", name: "Tom Dale" }, { id: "erik", name: "Erik Brynroflsson" } ]); } }); App.ItemRoute = Ember.Route.extend({ serialize(object) { return { id: object.id }; } }); bootApplication(); Ember.run(function() { router.handleURL("/about"); }); equal(Ember.$('h3:contains(List)', '#qunit-fixture').length, 1, "The home template was rendered"); equal(normalizeUrl(Ember.$('#home-link').attr('href')), '/', "The home link points back at /"); Ember.run(function() { Ember.$('li a:contains(Yehuda)', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Item)', '#qunit-fixture').length, 1, "The item template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Yehuda Katz", "The name is correct"); Ember.run(function() { Ember.$('#home-link').click(); }); Ember.run(function() { Ember.$('#about-link').click(); }); equal(normalizeUrl(Ember.$('li a:contains(Yehuda)').attr('href')), "/item/yehuda"); equal(normalizeUrl(Ember.$('li a:contains(Tom)').attr('href')), "/item/tom"); equal(normalizeUrl(Ember.$('li a:contains(Erik)').attr('href')), "/item/erik"); Ember.run(function() { Ember.$('li a:contains(Erik)', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Item)', '#qunit-fixture').length, 1, "The item template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Erik Brynroflsson", "The name is correct"); }); QUnit.test("The {{link-to}} helper binds some anchor html tag common attributes", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' title='title-attr' rel='rel-attr' tabindex='-1'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var link = Ember.$('#self-link', '#qunit-fixture'); equal(link.attr('title'), 'title-attr', "The self-link contains title attribute"); equal(link.attr('rel'), 'rel-attr', "The self-link contains rel attribute"); equal(link.attr('tabindex'), '-1', "The self-link contains tabindex attribute"); }); QUnit.test("The {{link-to}} helper supports `target` attribute", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' target='_blank'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var link = Ember.$('#self-link', '#qunit-fixture'); equal(link.attr('target'), '_blank', "The self-link contains `target` attribute"); }); QUnit.test("The {{link-to}} helper does not call preventDefault if `target` attribute is provided", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' target='_blank'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var event = Ember.$.Event("click"); Ember.$('#self-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), false, "should not preventDefault when target attribute is specified"); }); QUnit.test("The {{link-to}} helper should preventDefault when `target = _self`", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#link-to 'index' id='self-link' target='_self'}}Self{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var event = Ember.$.Event("click"); Ember.$('#self-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), true, "should preventDefault when target attribute is `_self`"); }); QUnit.test("The {{link-to}} helper should not transition if target is not equal to _self or empty", function() { Ember.TEMPLATES.index = compile("{{#link-to 'about' id='about-link' replace=true target='_blank'}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); notEqual(container.lookup('controller:application').get('currentRouteName'), 'about', 'link-to should not transition if target is not equal to _self or empty'); }); QUnit.test("The {{link-to}} helper accepts string/numeric arguments", function() { Router.map(function() { this.route('filter', { path: '/filters/:filter' }); this.route('post', { path: '/post/:post_id' }); this.route('repo', { path: '/repo/:owner/:name' }); }); App.FilterController = Ember.Controller.extend({ filter: "unpopular", repo: Ember.Object.create({ owner: 'ember', name: 'ember.js' }), post_id: 123 }); Ember.TEMPLATES.filter = compile('<p>{{filter}}</p>{{#link-to "filter" "unpopular" id="link"}}Unpopular{{/link-to}}{{#link-to "filter" filter id="path-link"}}Unpopular{{/link-to}}{{#link-to "post" post_id id="post-path-link"}}Post{{/link-to}}{{#link-to "post" 123 id="post-number-link"}}Post{{/link-to}}{{#link-to "repo" repo id="repo-object-link"}}Repo{{/link-to}}'); Ember.TEMPLATES.index = compile(' '); bootApplication(); Ember.run(function() { router.handleURL("/filters/popular"); }); equal(normalizeUrl(Ember.$('#link', '#qunit-fixture').attr('href')), "/filters/unpopular"); equal(normalizeUrl(Ember.$('#path-link', '#qunit-fixture').attr('href')), "/filters/unpopular"); equal(normalizeUrl(Ember.$('#post-path-link', '#qunit-fixture').attr('href')), "/post/123"); equal(normalizeUrl(Ember.$('#post-number-link', '#qunit-fixture').attr('href')), "/post/123"); equal(normalizeUrl(Ember.$('#repo-object-link', '#qunit-fixture').attr('href')), "/repo/ember/ember.js"); }); QUnit.test("Issue 4201 - Shorthand for route.index shouldn't throw errors about context arguments", function() { expect(2); Router.map(function() { this.resource('lobby', function() { this.route('index', { path: ':lobby_id' }); this.route('list'); }); }); App.LobbyIndexRoute = Ember.Route.extend({ model(params) { equal(params.lobby_id, 'foobar'); return params.lobby_id; } }); Ember.TEMPLATES['lobby/index'] = compile("{{#link-to 'lobby' 'foobar' id='lobby-link'}}Lobby{{/link-to}}"); Ember.TEMPLATES.index = compile(""); Ember.TEMPLATES['lobby/list'] = compile("{{#link-to 'lobby' 'foobar' id='lobby-link'}}Lobby{{/link-to}}"); bootApplication(); Ember.run(router, 'handleURL', '/lobby/list'); Ember.run(Ember.$('#lobby-link'), 'click'); shouldBeActive('#lobby-link'); }); QUnit.test("The {{link-to}} helper unwraps controllers", function() { if (isEnabled('ember-routing-transitioning-classes')) { expect(5); } else { expect(6); } Router.map(function() { this.route('filter', { path: '/filters/:filter' }); }); var indexObject = { filter: 'popular' }; App.FilterRoute = Ember.Route.extend({ model(params) { return indexObject; }, serialize(passedObject) { equal(passedObject, indexObject, "The unwrapped object is passed"); return { filter: 'popular' }; } }); App.IndexRoute = Ember.Route.extend({ model() { return indexObject; } }); Ember.TEMPLATES.filter = compile('<p>{{model.filter}}</p>'); Ember.TEMPLATES.index = compile('{{#link-to "filter" this id="link"}}Filter{{/link-to}}'); expectDeprecation(function() { bootApplication(); }, /Providing `{{link-to}}` with a param that is wrapped in a controller is deprecated./); Ember.run(function() { router.handleURL("/"); }); Ember.$('#link', '#qunit-fixture').trigger('click'); }); QUnit.test("The {{link-to}} helper doesn't change view context", function() { App.IndexView = EmberView.extend({ elementId: 'index', name: 'test', isTrue: true }); Ember.TEMPLATES.index = compile("{{view.name}}-{{#link-to 'index' id='self-link'}}Link: {{view.name}}-{{#if view.isTrue}}{{view.name}}{{/if}}{{/link-to}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(Ember.$('#index', '#qunit-fixture').text(), 'test-Link: test-test', "accesses correct view"); }); QUnit.test("Quoteless route param performs property lookup", function() { Ember.TEMPLATES.index = compile("{{#link-to 'index' id='string-link'}}string{{/link-to}}{{#link-to foo id='path-link'}}path{{/link-to}}{{#link-to view.foo id='view-link'}}{{view.foo}}{{/link-to}}"); function assertEquality(href) { equal(normalizeUrl(Ember.$('#string-link', '#qunit-fixture').attr('href')), '/'); equal(normalizeUrl(Ember.$('#path-link', '#qunit-fixture').attr('href')), href); equal(normalizeUrl(Ember.$('#view-link', '#qunit-fixture').attr('href')), href); } App.IndexView = EmberView.extend({ foo: 'index', elementId: 'index-view' }); App.IndexController = Ember.Controller.extend({ foo: 'index' }); App.Router.map(function() { this.route('about'); }); bootApplication(); Ember.run(router, 'handleURL', '/'); assertEquality('/'); var controller = container.lookup('controller:index'); var view = EmberView.views['index-view']; Ember.run(function() { controller.set('foo', 'about'); view.set('foo', 'about'); }); assertEquality('/about'); }); QUnit.test("link-to with null/undefined dynamic parameters are put in a loading state", function() { expect(19); var oldWarn = Ember.Logger.warn; var warnCalled = false; Ember.Logger.warn = function() { warnCalled = true; }; Ember.TEMPLATES.index = compile("{{#link-to destinationRoute routeContext loadingClass='i-am-loading' id='context-link'}}string{{/link-to}}{{#link-to secondRoute loadingClass='i-am-loading' id='static-link'}}string{{/link-to}}"); var thing = Ember.Object.create({ id: 123 }); App.IndexController = Ember.Controller.extend({ destinationRoute: null, routeContext: null }); App.AboutRoute = Ember.Route.extend({ activate() { ok(true, "About was entered"); } }); App.Router.map(function() { this.route('thing', { path: '/thing/:thing_id' }); this.route('about'); }); bootApplication(); Ember.run(router, 'handleURL', '/'); function assertLinkStatus($link, url) { if (url) { equal(normalizeUrl($link.attr('href')), url, "loaded link-to has expected href"); ok(!$link.hasClass('i-am-loading'), "loaded linkComponent has no loadingClass"); } else { equal(normalizeUrl($link.attr('href')), '#', "unloaded link-to has href='#'"); ok($link.hasClass('i-am-loading'), "loading linkComponent has loadingClass"); } } var $contextLink = Ember.$('#context-link', '#qunit-fixture'); var $staticLink = Ember.$('#static-link', '#qunit-fixture'); var controller = container.lookup('controller:index'); assertLinkStatus($contextLink); assertLinkStatus($staticLink); Ember.run(function() { warnCalled = false; $contextLink.click(); ok(warnCalled, "Logger.warn was called from clicking loading link"); }); // Set the destinationRoute (context is still null). Ember.run(controller, 'set', 'destinationRoute', 'thing'); assertLinkStatus($contextLink); // Set the routeContext to an id Ember.run(controller, 'set', 'routeContext', '456'); assertLinkStatus($contextLink, '/thing/456'); // Test that 0 isn't interpreted as falsy. Ember.run(controller, 'set', 'routeContext', 0); assertLinkStatus($contextLink, '/thing/0'); // Set the routeContext to an object Ember.run(controller, 'set', 'routeContext', thing); assertLinkStatus($contextLink, '/thing/123'); // Set the destinationRoute back to null. Ember.run(controller, 'set', 'destinationRoute', null); assertLinkStatus($contextLink); Ember.run(function() { warnCalled = false; $staticLink.click(); ok(warnCalled, "Logger.warn was called from clicking loading link"); }); Ember.run(controller, 'set', 'secondRoute', 'about'); assertLinkStatus($staticLink, '/about'); // Click the now-active link Ember.run($staticLink, 'click'); Ember.Logger.warn = oldWarn; }); QUnit.test("The {{link-to}} helper refreshes href element when one of params changes", function() { Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); var post = Ember.Object.create({ id: '1' }); var secondPost = Ember.Object.create({ id: '2' }); Ember.TEMPLATES.index = compile('{{#link-to "post" post id="post"}}post{{/link-to}}'); App.IndexController = Ember.Controller.extend(); var indexController = container.lookup('controller:index'); Ember.run(function() { indexController.set('post', post); }); bootApplication(); Ember.run(function() { router.handleURL("/"); }); equal(normalizeUrl(Ember.$('#post', '#qunit-fixture').attr('href')), '/posts/1', 'precond - Link has rendered href attr properly'); Ember.run(function() { indexController.set('post', secondPost); }); equal(Ember.$('#post', '#qunit-fixture').attr('href'), '/posts/2', 'href attr was updated after one of the params had been changed'); Ember.run(function() { indexController.set('post', null); }); equal(Ember.$('#post', '#qunit-fixture').attr('href'), '#', 'href attr becomes # when one of the arguments in nullified'); }); QUnit.test("The {{link-to}} helper's bound parameter functionality works as expected in conjunction with an ObjectProxy/Controller", function() { expectDeprecation(objectControllerDeprecation); Router.map(function() { this.route('post', { path: '/posts/:post_id' }); }); var post = Ember.Object.create({ id: '1' }); var secondPost = Ember.Object.create({ id: '2' }); Ember.TEMPLATES = { index: compile(' '), post: compile('{{#link-to "post" this id="self-link"}}selflink{{/link-to}}') }; App.PostController = Ember.ObjectController.extend(); var postController = container.lookup('controller:post'); bootApplication(); Ember.run(router, 'transitionTo', 'post', post); var $link = Ember.$('#self-link', '#qunit-fixture'); equal(normalizeUrl($link.attr('href')), '/posts/1', 'self link renders post 1'); Ember.run(postController, 'set', 'model', secondPost); equal(normalizeUrl($link.attr('href')), '/posts/2', 'self link updated to post 2'); }); QUnit.test("{{linkTo}} is aliased", function() { Ember.TEMPLATES.index = compile("<h3>Home</h3>{{#linkTo 'about' id='about-link' replace=true}}About{{/linkTo}}"); Router.map(function() { this.route("about"); }); expectDeprecation(function() { bootApplication(); }, "The 'linkTo' view helper is deprecated in favor of 'link-to'"); Ember.run(function() { router.handleURL("/"); }); Ember.run(function() { Ember.$('#about-link', '#qunit-fixture').click(); }); equal(container.lookup('controller:application').get('currentRouteName'), 'about', 'linkTo worked properly'); }); QUnit.test("The {{link-to}} helper is active when a resource is active", function() { Router.map(function() { this.resource("about", function() { this.route("item"); }); }); Ember.TEMPLATES.about = compile("<div id='about'>{{#link-to 'about' id='about-link'}}About{{/link-to}} {{#link-to 'about.item' id='item-link'}}Item{{/link-to}} {{outlet}}</div>"); Ember.TEMPLATES['about/item'] = compile(" "); Ember.TEMPLATES['about/index'] = compile(" "); bootApplication(); Ember.run(router, 'handleURL', '/about'); equal(Ember.$('#about-link.active', '#qunit-fixture').length, 1, "The about resource link is active"); equal(Ember.$('#item-link.active', '#qunit-fixture').length, 0, "The item route link is inactive"); Ember.run(router, 'handleURL', '/about/item'); equal(Ember.$('#about-link.active', '#qunit-fixture').length, 1, "The about resource link is active"); equal(Ember.$('#item-link.active', '#qunit-fixture').length, 1, "The item route link is active"); }); QUnit.test("The {{link-to}} helper works in an #each'd array of string route names", function() { Router.map(function() { this.route('foo'); this.route('bar'); this.route('rar'); }); App.IndexController = Ember.Controller.extend({ routeNames: Ember.A(['foo', 'bar', 'rar']), route1: 'bar', route2: 'foo' }); Ember.TEMPLATES = { index: compile('{{#each routeNames as |routeName|}}{{#link-to routeName}}{{routeName}}{{/link-to}}{{/each}}{{#each routeNames as |r|}}{{#link-to r}}{{r}}{{/link-to}}{{/each}}{{#link-to route1}}a{{/link-to}}{{#link-to route2}}b{{/link-to}}') }; bootApplication(); function linksEqual($links, expected) { equal($links.length, expected.length, "Has correct number of links"); var idx; for (idx = 0; idx < $links.length; idx++) { var href = Ember.$($links[idx]).attr('href'); // Old IE includes the whole hostname as well equal(href.slice(-expected[idx].length), expected[idx], "Expected link to be '"+expected[idx]+"', but was '"+href+"'"); } } linksEqual(Ember.$('a', '#qunit-fixture'), ["/foo", "/bar", "/rar", "/foo", "/bar", "/rar", "/bar", "/foo"]); var indexController = container.lookup('controller:index'); Ember.run(indexController, 'set', 'route1', 'rar'); linksEqual(Ember.$('a', '#qunit-fixture'), ["/foo", "/bar", "/rar", "/foo", "/bar", "/rar", "/rar", "/foo"]); Ember.run(indexController.routeNames, 'shiftObject'); linksEqual(Ember.$('a', '#qunit-fixture'), ["/bar", "/rar", "/bar", "/rar", "/rar", "/foo"]); }); QUnit.test("The non-block form {{link-to}} helper moves into the named route", function() { expect(3); Router.map(function(match) { this.route("contact"); }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{link-to 'Contact us' 'contact' id='contact-link'}}{{#link-to 'index' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.contact = compile("<h3>Contact</h3>{{link-to 'Home' 'index' id='home-link'}}{{link-to 'Self' 'contact' id='self-link'}}"); bootApplication(); Ember.run(function() { Ember.$('#contact-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Contact)', '#qunit-fixture').length, 1, "The contact template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#home-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); }); QUnit.test("The non-block form {{link-to}} helper updates the link text when it is a binding", function() { expect(8); Router.map(function(match) { this.route("contact"); }); App.IndexController = Ember.Controller.extend({ contactName: 'Jane' }); Ember.TEMPLATES.index = compile("<h3>Home</h3>{{link-to contactName 'contact' id='contact-link'}}{{#link-to 'index' id='self-link'}}Self{{/link-to}}"); Ember.TEMPLATES.contact = compile("<h3>Contact</h3>{{link-to 'Home' 'index' id='home-link'}}{{link-to 'Self' 'contact' id='self-link'}}"); bootApplication(); Ember.run(function() { router.handleURL("/"); }); var controller = container.lookup('controller:index'); equal(Ember.$('#contact-link:contains(Jane)', '#qunit-fixture').length, 1, "The link title is correctly resolved"); Ember.run(function() { controller.set('contactName', 'Joe'); }); equal(Ember.$('#contact-link:contains(Joe)', '#qunit-fixture').length, 1, "The link title is correctly updated when the bound property changes"); Ember.run(function() { controller.set('contactName', 'Robert'); }); equal(Ember.$('#contact-link:contains(Robert)', '#qunit-fixture').length, 1, "The link title is correctly updated when the bound property changes a second time"); Ember.run(function() { Ember.$('#contact-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Contact)', '#qunit-fixture').length, 1, "The contact template was rendered"); equal(Ember.$('#self-link.active', '#qunit-fixture').length, 1, "The self-link was rendered with active class"); equal(Ember.$('#home-link:not(.active)', '#qunit-fixture').length, 1, "The other link was rendered without active class"); Ember.run(function() { Ember.$('#home-link', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Home)', '#qunit-fixture').length, 1, "The index template was rendered"); equal(Ember.$('#contact-link:contains(Robert)', '#qunit-fixture').length, 1, "The link title is correctly updated when the route changes"); }); QUnit.test("The non-block form {{link-to}} helper moves into the named route with context", function() { expect(5); Router.map(function(match) { this.route("item", { path: "/item/:id" }); }); App.IndexRoute = Ember.Route.extend({ model() { return Ember.A([ { id: "yehuda", name: "Yehuda Katz" }, { id: "tom", name: "Tom Dale" }, { id: "erik", name: "Erik Brynroflsson" } ]); } }); App.ItemRoute = Ember.Route.extend({ serialize(object) { return { id: object.id }; } }); Ember.TEMPLATES.index = compile("<h3>Home</h3><ul>{{#each controller as |person|}}<li>{{link-to person.name 'item' person}}</li>{{/each}}</ul>"); Ember.TEMPLATES.item = compile("<h3>Item</h3><p>{{model.name}}</p>{{#link-to 'index' id='home-link'}}Home{{/link-to}}"); bootApplication(); Ember.run(function() { Ember.$('li a:contains(Yehuda)', '#qunit-fixture').click(); }); equal(Ember.$('h3:contains(Item)', '#qunit-fixture').length, 1, "The item template was rendered"); equal(Ember.$('p', '#qunit-fixture').text(), "Yehuda Katz", "The name is correct"); Ember.run(function() { Ember.$('#home-link').click(); }); equal(normalizeUrl(Ember.$('li a:contains(Yehuda)').attr('href')), "/item/yehuda"); equal(normalizeUrl(Ember.$('li a:contains(Tom)').attr('href')), "/item/tom"); equal(normalizeUrl(Ember.$('li a:contains(Erik)').attr('href')), "/item/erik"); }); QUnit.test("The non-block form {{link-to}} performs property lookup", function() { Ember.TEMPLATES.index = compile("{{link-to 'string' 'index' id='string-link'}}{{link-to path foo id='path-link'}}{{link-to view.foo view.foo id='view-link'}}"); function assertEquality(href) { equal(normalizeUrl(Ember.$('#string-link', '#qunit-fixture').attr('href')), '/'); equal(normalizeUrl(Ember.$('#path-link', '#qunit-fixture').attr('href')), href); equal(normalizeUrl(Ember.$('#view-link', '#qunit-fixture').attr('href')), href); } App.IndexView = EmberView.extend({ foo: 'index', elementId: 'index-view' }); App.IndexController = Ember.Controller.extend({ foo: 'index' }); App.Router.map(function() { this.route('about'); }); bootApplication(); Ember.run(router, 'handleURL', '/'); assertEquality('/'); var controller = container.lookup('controller:index'); var view = EmberView.views['index-view']; Ember.run(function() { controller.set('foo', 'about'); view.set('foo', 'about'); }); assertEquality('/about'); }); QUnit.test("The non-block form {{link-to}} protects against XSS", function() { Ember.TEMPLATES.application = compile("{{link-to display 'index' id='link'}}"); App.ApplicationController = Ember.Controller.extend({ display: 'blahzorz' }); bootApplication(); Ember.run(router, 'handleURL', '/'); var controller = container.lookup('controller:application'); equal(Ember.$('#link', '#qunit-fixture').text(), 'blahzorz'); Ember.run(function() { controller.set('display', '<b>BLAMMO</b>'); }); equal(Ember.$('#link', '#qunit-fixture').text(), '<b>BLAMMO</b>'); equal(Ember.$('b', '#qunit-fixture').length, 0); }); QUnit.test("the {{link-to}} helper calls preventDefault", function() { Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(router, 'handleURL', '/'); var event = Ember.$.Event("click"); Ember.$('#about-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), true, "should preventDefault"); }); QUnit.test("the {{link-to}} helper does not call preventDefault if `preventDefault=false` is passed as an option", function() { Ember.TEMPLATES.index = compile("{{#link-to 'about' id='about-link' preventDefault=false}}About{{/link-to}}"); Router.map(function() { this.route("about"); }); bootApplication(); Ember.run(router, 'handleURL', '/'); var event = Ember.$.Event("click"); Ember.$('#about-link', '#qunit-fixture').trigger(event); equal(event.isDefaultPrevented(), false, "should not preventDefault"); }); QUnit.test("the {{link-to}} helper does not throw an error if its route has exited", function() { expect(0); Ember.TEMPLATES.application = compile("{{#link-to 'index' id='home-link'}}Home{{/link-to}}{{#link-to 'post' defaultPost id='default-post-link'}}Default Post{{/link-to}}{{#if currentPost}}{{#link-to 'post' id='post-link'}}Post{{/link-to}}{{/if}}"); App.ApplicationController = Ember.Controller.extend({ needs: ['post'], currentPost: Ember.computed.alias('controllers.post.model') }); App.PostController = Ember.Controller.extend({ model: { id: 1 } }); Router.map(function() { this.route("post", { path: 'post/:post_id' }); }); bootApplication(); Ember.run(router, 'handleURL', '/'); Ember.run(function() { Ember.$('#default-post-link', '#qunit-fixture').click(); }); Ember.run(function() { Ember.$('#home-link', '#qunit-fixture').click(); }); }); QUnit.test("{{link-to}} active property respects changing parent route context", function() { Ember.TEMPLATES.application = compile( "{{link-to 'OMG' 'things' 'omg' id='omg-link'}} " + "{{link-to 'LOL' 'things' 'lol' id='lol-link'}} "); Router.map(function() { this.resource('things', { path: '/things/:name' }, function() { this.route('other'); }); }); bootApplication(); Ember.run(router, 'handleURL', '/things/omg'); shouldBeActive('#omg-link'); shouldNotBeActive('#lol-link'); Ember.run(router, 'handleURL', '/things/omg/other'); shouldBeActive('#omg-link'); shouldNotBeActive('#lol-link'); }); QUnit.test("{{link-to}} populates href with default query param values even without query-params object", function() { if (isEnabled('ember-routing-route-configured-query-params')) { App.IndexRoute = Ember.Route.extend({ queryParams: { foo: { defaultValue: '123' } } }); } else { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123' }); } Ember.TEMPLATES.index = compile("{{#link-to 'index' id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/", "link has right href"); }); QUnit.test("{{link-to}} populates href with default query param values with empty query-params object", function() { if (isEnabled('ember-routing-route-configured-query-params')) { App.IndexRoute = Ember.Route.extend({ queryParams: { foo: { defaultValue: '123' } } }); } else { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123' }); } Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params) id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/", "link has right href"); }); QUnit.test("{{link-to}} populates href with supplied query param values", function() { if (isEnabled('ember-routing-route-configured-query-params')) { App.IndexRoute = Ember.Route.extend({ queryParams: { foo: { defaultValue: '123' } } }); } else { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123' }); } Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='456') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/?foo=456", "link has right href"); }); QUnit.test("{{link-to}} populates href with partially supplied query param values", function() { if (isEnabled('ember-routing-route-configured-query-params')) { App.IndexRoute = Ember.Route.extend({ queryParams: { foo: { defaultValue: '123' }, bar: { defaultValue: 'yes' } } }); } else { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123', bar: 'yes' }); } Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='456') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/?foo=456", "link has right href"); }); QUnit.test("{{link-to}} populates href with partially supplied query param values, but omits if value is default value", function() { if (isEnabled('ember-routing-route-configured-query-params')) { App.IndexRoute = Ember.Route.extend({ queryParams: { foo: { defaultValue: '123' } } }); } else { App.IndexController = Ember.Controller.extend({ queryParams: ['foo'], foo: '123' }); } Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='123') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/", "link has right href"); }); QUnit.test("{{link-to}} populates href with fully supplied query param values", function() { if (isEnabled('ember-routing-route-configured-query-params')) { App.IndexRoute = Ember.Route.extend({ queryParams: { foo: { defaultValue: '123' }, bar: { defaultValue: 'yes' } } }); } else { App.IndexController = Ember.Controller.extend({ queryParams: ['foo', 'bar'], foo: '123', bar: 'yes' }); } Ember.TEMPLATES.index = compile("{{#link-to 'index' (query-params foo='456' bar='NAW') id='the-link'}}Index{{/link-to}}"); bootApplication(); equal(Ember.$('#the-link').attr('href'), "/?bar=NAW&foo=456", "link has right href"); });
thejameskyle/ember.js
packages/ember/tests/helpers/link_to_test.js
JavaScript
mit
43,612
var SafeObject = require('../../dist/SafeObject.js'); function Human(name) { SafeObject.call(this); this.name = name; } Human.prototype = Object.create(SafeObject && SafeObject.prototype, { constructor: { value: Human, enumerable: false, writable: true, configurable: true } }); Human.INSTANCE_PROPERTIES = { leftArm: null, rightArm: null, leftLeg: null, rightLeg: null, isHuman: new SafeObject.PropertyDescriptor(true, true, false, false) }; module.exports = Human;
Kelgors/SafeObject.js
tests/things/Human.js
JavaScript
mit
495
hackApp.service( 'ApiService', [ '$resource', function ( $resource ) { return $resource('http://74.208.124.117/www/api/apiIndex.php/', {}, { login : { url : 'http://74.208.124.117/www/api/apiIndex.php/login', method : 'POST', params : { }, transformRequest : function ( data ) { var info = { token : data.token }; return angular.toJson( info ); }, isArray : true }, listServers : { url : 'http://74.208.124.117/www/api/apiIndex.php/servers', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true, ignoreLoadingBar: true }, restartServer : { url : 'http://74.208.124.117/www/api/apiIndex.php/servers/:id/restart', method : 'PUT', params : { id : '@id' }, transformRequest : function ( data ) { var info = { action: 'restart' }; return angular.toJson( info ); }, isArray : false }, listLoadBalancers : { url : 'http://74.208.124.117/www/api/apiIndex.php/load_balancers', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true }, listFirewallPolicies : { url : 'http://74.208.124.117/www/api/apiIndex.php/firewall_policies', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true }, listSharedStorage : { url : 'http://74.208.124.117/www/api/apiIndex.php/shared_storages', method : 'GET', params : { }, transformRequest : function ( data ) { var info = { }; return angular.toJson( info ); }, isArray : true }, callMethod : { url : 'http://74.208.124.117/www/api/apiIndex.php/login', method : 'POST', params : { }, transformRequest : function ( data ) { var info = { token : data.token }; return angular.toJson( info ); }, isArray : true } } ); } ] ); // hackApp.service( 'ApiService', [ '$resource', function ( $resource ) { // return $resource( // 'user_logs', {}, { // query : { // url : 'user_logs', // method : 'GET', // params : { // }, // isArray : true // }, // get : { // url : 'user_logs/:id', // method : 'GET', // params : { // id : '@id' // }, // isArray : false // } // } // ); // } ] );
vilazae/ngcs-hack
www/app/common/services/apiServices.js
JavaScript
mit
3,398
var immediateAuth = false; var Neutron = { gdrive_api_loaded: false, authorized: false, authorizer: null, OAuth: null, UserId: null, parent: null, origin: null, id: null, init_token: null, share: null }; Neutron.auth_init = function (setkey, force_slow) { if (setkey) { gapi.client.setApiKey(GOOGLE_KEY); } if (!Neutron.parent) { setTimeout(Neutron.auth_init, 300); return 0; } if (!Neutron.gdrive_api_loaded) { gapi.client.load('drive', 'v2', function () { Neutron.gdrive_api_loaded = true; Neutron.auth_init(); }); return 0; } if (Neutron.authorizer) { clearTimeout(Neutron.authorizer); Neutron.authorizer = null; } var options = { client_id: GOOGLE_CLIENT_ID, immediate: immediateAuth, scope: [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.scripts', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/drive.install', 'https://www.googleapis.com/auth/drive.file' ] }; if (Neutron.UserId) { options.user_id = Neutron.UserId; } if (force_slow) { options.immediate = false; } gapi.auth.authorize(options, Neutron.auth_callback); }; Neutron.auth_callback = function (OAuth) { Neutron.parent.postMessage({'task': 'close-popup', id: Neutron.id}, Neutron.origin); if (OAuth && OAuth.error) { Neutron.auth_init(false, true); return null; } if (OAuth && OAuth.expires_in) { try { gapi.drive.realtime.setServerAddress('https://docs.google.com/otservice/'); } catch (e) { setTimeout(Neutron.auth_init, 300); return 0; } Neutron.OAuth = OAuth; Neutron.authorizer = setTimeout(Neutron.auth_init, 60 * 25 * 1000); Neutron.authorized = true; oauth = { access_token: OAuth.access_token, expires_at: OAuth.expires_at }; gapi.client.load('oauth2', 'v2', function() { gapi.client.oauth2.userinfo.get().execute(function (resp) { oauth.user_id = resp.id; Neutron.UserId = resp.id; var request = gapi.client.drive.about.get(); request.execute(function (response) { document.querySelector("#email").innerHTML = 'Account: ' + response.user.emailAddress; immediateAuth = true; Neutron.parent.postMessage({ task: 'token', oauth: oauth, email: response.user.emailAddress, id: Neutron.id }, Neutron.origin); }); }); }); } }; Neutron.pick_folder = function () { var docsView = new google.picker.DocsView(). setIncludeFolders(true). setMimeTypes('application/vnd.google-apps.folder'). setSelectFolderEnabled(true); var picker = new google.picker.PickerBuilder(). addView(docsView). setOAuthToken(Neutron.OAuth.access_token). setDeveloperKey(GOOGLE_KEY). setCallback(Neutron.pick_folder_callback). build(); picker.setVisible(true); }; Neutron.pick_folder_callback = function (data) { if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) { var doc = data[google.picker.Response.DOCUMENTS][0]; var id = doc[google.picker.Document.ID]; Neutron.parent.postMessage({'task': 'folder-picked', id: Neutron.id, folderId: id}, Neutron.origin); } else if (data[google.picker.Response.ACTION] == google.picker.Action.CANCEL) { Neutron.parent.postMessage({'task': 'hide-webview', id: Neutron.id}, Neutron.origin); } }; Neutron.receive_message = function (event) { if (event.data && event.data.task) { if (event.data.task === 'handshake') { if (!Neutron.parent) { Neutron.parent = event.source; Neutron.origin = event.origin; Neutron.id = event.data.id; if (event.data.oauth) { document.querySelector("#email").innerHTML = 'Initializing Account: ' + event.data.email; gapi.load('auth:client,drive-realtime,drive-share,picker', function () { gapi.auth.setToken({ access_token: event.data.oauth.access_token }); Neutron.UserId = event.data.oauth.user_id; Neutron.auth_init(true); }); } else { gapi.load('auth:client,drive-realtime,drive-share,picker', function () { Neutron.auth_init(true); }); } } } else if (event.data.task === 'reauth') { Neutron.auth_init(true); } else if (event.data.task === 'pick-folder') { Neutron.pick_folder(); } else if (Drive[event.data.task]) { Drive[event.data.task](event.data, function (result) { Neutron.parent.postMessage({ 'task': event.data.task, id: Neutron.id, result: result, pid: event.data.pid }, Neutron.origin); }); } } }; window.addEventListener("message", Neutron.receive_message, false); function report_error (error, data) { var post_data = { error: JSON.stringify(error), data: JSON.stringify(data), apikey: 'errors-are-a-bitch', username: 'GDrive-' + document.querySelector("#email").innerHTML }; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", '/editor/error', true); xmlhttp.send(JSON.stringify(post_data)); } window.onerror = function (msg, url, line) { report_error(msg, {url: url, line: line}); };
pizzapanther/Super-Neutron-Drive
server/ndrive/static/js/neutron.js
JavaScript
mit
5,469
import Form from './Form'; import CheckboxList from './CheckboxList'; import RadioList from './RadioList'; import Select from './Select'; import TextInput from './TextInput'; Form.CheckboxList = CheckboxList; Form.RadioList = RadioList; Form.Select = Select; Form.TextInput = TextInput; export default Form;
e1-bsd/omni-common-ui
src/components/Form/index.js
JavaScript
mit
310
import { COLUMN_NAMES, COLUMNS } from './table.constant' export function format(columnName, contents) { switch (columnName) { case COLUMN_NAMES.NUMBER: return contents.slice(0, 2) + '-' + contents.slice(2) default: return contents } } export function generateComparisonFunction(sortingOrder, i) { const key = COLUMNS[i] return (a, b) => sortingOrder * (a[key] > b[key] ? 1 : a[key] < b[key] ? -1 : 0) }
gchatterjee/cit-gened-finder
ui/src/components/table/table.action.js
JavaScript
mit
448
/** * @author Gabriel Dodan , [email protected] * @copyright Copyright (c) 2012 Gabriel Dodan * @license The MIT License http://www.opensource.org/licenses/mit-license.php , see LICENSE.txt file also */ /** @DEPENDENCIES = ["FORMS_LIB/controls/ListControl.js"]; */ /* wrapper for <select> tag */ Pd.Forms.Select = Pd.Forms.ListControl.extend({ init: function(name, config) { this._super(name, config); }, content : function() { var defaultAttrs = { id : this.id, name : (this.config.multipleSelect ? this.name + "[]" : this.name) }; if ( this.config.multipleSelect ) { defaultAttrs.multiple="multiple"; } var excludeAttrs = Pd.Forms.propsToArray(defaultAttrs); excludeAttrs.push("multiple"); var val, label; for(var i=0; i<this.config.dataSet.length; i++) { val = this.config.dataSet[i][0]; label = this.config.dataSet[i][1]; this.items.push( new Pd.Forms.SelectItem(val, label, Pd.Forms.inArray(val, this.config.selectedValues)) ); } var content = '' + '<select ' + Pd.Forms.objAsAttrs(defaultAttrs) + ' ' + Pd.Forms.objAsAttrs(this.config.attrs, excludeAttrs) + '>\n' + (this.config.itemsRenderer != null ? this.config.itemsRenderer(this) : this.defaultItemsRenderer(this) ) + '\n' + '</select>' ; return content + Pd.Forms.codeForBinds(this.id, this.config.binds); }, defaultItemsRenderer : function(control) { var content = []; for (var i=0; i<control.items.length; i++) { content.push( control.items[i].content() ); } return content.join("\n"); }, getValue : function() { return $("#" + this.id).val(); }, getSelectedValues : function() { return this.getValue(); } }); /* wrapper for <option> tag */ Pd.Forms.SelectItem = Pd.Forms.ListControlItem.extend({ init:function(value, label, isSelected) { this._super(value, label, isSelected); }, content:function() { var defaultAttrs = { value:this.value }; if ( this.isSelected ) { defaultAttrs.selected="selected"; } var excludeAttrs = Pd.Forms.propsToArray(defaultAttrs); excludeAttrs.push("selected"); return '<option ' + Pd.Forms.objAsAttrs(defaultAttrs) + ' ' + Pd.Forms.objAsAttrs(this.attrs, excludeAttrs) + '>' + Pd.Forms.escape(this.label) + '</option>'; } }); /* config = { name:"name", dataSet:[], selectedValues:[], multipleSelect:true|false, itemsRenderer:function(control){}, attrs:{ }, binds:{ }, validators:{ } } */
gabrieldodan/php-dancer
system/libraries/Forms/controls/Select.js
JavaScript
mit
2,461
'use strict'; (function(module) { const repos = {}; repos.all = []; repos.requestRepos = function(callback) { $.get('/github/user/repos') .then(data => repos.all = data, err => console.error(err)) .then(callback(repos)); }; repos.with = attr => repos.all.filter(repo => repo[attr]); module.repos = repos; })(window);
Jamesbillard12/jamesPortfolio
public/js/repo.js
JavaScript
mit
347