Repository: xueduany/react-mix Branch: master Commit: 1806247d3908 Files: 154 Total size: 1.9 MB Directory structure: gitextract_eh8az0r_/ ├── README.md ├── build/ │ ├── part1.js │ └── part2.js ├── css/ │ ├── cxylhl/ │ │ └── index.css │ ├── game/ │ │ └── game2048.css │ ├── jqueryapi.css │ ├── lightningStorm.css │ ├── vsImgList.css │ └── vsIndex.css ├── dev.sh ├── install.sh ├── native-css.js ├── package.json ├── react-native.js.split.build.js ├── react.css.build.js ├── reactnative/ │ ├── 2048/ │ │ ├── components/ │ │ │ ├── aboveGame.js │ │ │ ├── container.js │ │ │ ├── gameContainer.js │ │ │ ├── gameMessage.js │ │ │ ├── gridCell.js │ │ │ ├── gridContainer.js │ │ │ ├── gridRow.js │ │ │ ├── heading.js │ │ │ ├── tile.js │ │ │ └── tileContainer.js │ │ ├── game.js │ │ └── utils/ │ │ ├── grid.js │ │ ├── localStorageManager.js │ │ └── tile.js │ ├── README.md │ ├── android/ │ │ ├── app/ │ │ │ ├── app.iml │ │ │ ├── build.gradle │ │ │ ├── proguard-rules.pro │ │ │ ├── react.gradle │ │ │ └── src/ │ │ │ └── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── java/ │ │ │ │ └── com/ │ │ │ │ └── reactnative/ │ │ │ │ └── MainActivity.java │ │ │ └── res/ │ │ │ ├── menu/ │ │ │ │ └── menu_main_activity2.xml │ │ │ ├── values/ │ │ │ │ ├── dimens.xml │ │ │ │ ├── strings.xml │ │ │ │ └── styles.xml │ │ │ └── values-w820dp/ │ │ │ └── dimens.xml │ │ ├── build.gradle │ │ ├── gradle/ │ │ │ └── wrapper/ │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ │ ├── gradle.properties │ │ ├── gradlew │ │ ├── gradlew.bat │ │ ├── reactnative.iml │ │ └── settings.gradle │ ├── canvasgame/ │ │ ├── Canvas.js │ │ ├── GallaxyOctopus.js │ │ ├── game.js │ │ └── parts/ │ │ ├── Counter.js │ │ ├── Octopus.js │ │ └── Pipe.js │ ├── common/ │ │ ├── Animation.js │ │ ├── App.js │ │ ├── Date.js │ │ ├── DomEvent.js │ │ ├── LightningStorm.js │ │ ├── LocalStorage.js │ │ ├── StateStore.js │ │ ├── String.js │ │ ├── StyleSheet.js │ │ ├── TimerMixin.js │ │ ├── console.js │ │ └── rn/ │ │ ├── A.js │ │ ├── Body.js │ │ ├── Button.js │ │ ├── Carousel.js │ │ ├── Div.js │ │ ├── Element.js │ │ ├── Header.js │ │ ├── HtmlCssParser.js │ │ ├── Img.js │ │ ├── Input.js │ │ ├── Nav.js │ │ ├── RightSliderMenu.js │ │ ├── SimpleListView.js │ │ ├── Span.js │ │ ├── Tab.js │ │ ├── TabItem.js │ │ └── TabSlider.js │ ├── css/ │ │ ├── cxylhl/ │ │ │ └── index.js │ │ ├── game/ │ │ │ └── game2048.js │ │ ├── jqueryapi.js │ │ ├── lightningStorm.js │ │ ├── vsImgList.js │ │ └── vsIndex.js │ ├── cxylhl.js │ ├── example_addEventListener.js │ ├── example_animation.js │ ├── example_formElement.js │ ├── example_jqueryapi.js │ ├── example_listview.js │ ├── example_localStorage.js │ ├── example_onclick.js │ ├── example_ontouch.js │ ├── example_view.js │ ├── index.android.js │ ├── index.ios.js │ ├── index.js │ ├── ios/ │ │ ├── native/ │ │ │ ├── AppDelegate.h │ │ │ ├── AppDelegate.m │ │ │ ├── Base.lproj/ │ │ │ │ └── LaunchScreen.xib │ │ │ ├── Images.xcassets/ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── Brand Assets.launchimage/ │ │ │ │ │ └── Contents.json │ │ │ │ ├── Contents.json │ │ │ │ ├── LaunchImage.launchimage/ │ │ │ │ │ └── Contents.json │ │ │ │ └── icon-1024.imageset/ │ │ │ │ └── Contents.json │ │ │ ├── Info.plist │ │ │ └── main.m │ │ ├── native.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ └── xcshareddata/ │ │ │ └── xcschemes/ │ │ │ └── native.xcscheme │ │ └── nativeTests/ │ │ ├── Info.plist │ │ └── nativeTests.m │ ├── package.json │ ├── testFlex.js │ ├── testLineHeight.js │ ├── testScroll.js │ ├── vsImgList.js │ ├── vsIndex.js │ └── webpack.config.js ├── web/ │ ├── common/ │ │ ├── html/ │ │ │ ├── A.js │ │ │ ├── Button.js │ │ │ ├── Carousel.js │ │ │ ├── Div.js │ │ │ ├── Element.js │ │ │ ├── Header.js │ │ │ ├── Img.js │ │ │ ├── Input.js │ │ │ ├── ListView/ │ │ │ │ ├── ListView.js │ │ │ │ ├── ListViewDataSource.js │ │ │ │ ├── ScrollResponder.js │ │ │ │ └── StaticRenderer.js │ │ │ ├── ListView.js │ │ │ ├── NavBar.js │ │ │ ├── Navigator.js │ │ │ ├── RightSliderMenu.js │ │ │ ├── ScrollView/ │ │ │ │ └── ScrollView.js │ │ │ ├── ScrollView.js │ │ │ ├── SimpleListView.js │ │ │ ├── Span.js │ │ │ ├── TabSlider.js │ │ │ ├── Utilties/ │ │ │ │ ├── ErrorUitls.js │ │ │ │ ├── LayoutMixin.js │ │ │ │ ├── dismissKeyboard.js │ │ │ │ ├── getLayout.js │ │ │ │ └── setNativeProps.js │ │ │ └── View/ │ │ │ └── View.js │ │ ├── react.js │ │ └── ui.js │ └── index.html └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: README.md ================================================ # React Mix React Mix enables you to build all platform application base on React-Native. We create a mid-layer to support all CSS gramma, all JS dom event, all H5 framework on React-Native, and We have done these: - support CSS className - support CSS unit, px, pt, rem, em - unify box model measurement on all platform by CSS rem - support CSS two or more className combine or inherit, such as (.className1 .className2 .className3...)inhreit , (.className1.className2.className3)combine - support CSS selector(part done, progress), have support #id, .className, tagName - support DOM selector(part done, progress), have support $('#id'), $('.className'), $('TagName'), $('CSS3 selector')(by sizzle) - support DOM event, like onTouchXXXX, onLoad, onClick...eg(done) - support DOM Manipulation API like JQuery(part done, progress), have support part JQuery DOM API, all done until February - support ReactNative Bundle into two part, not single release, one is like common part, include nessesary component, bigger one, another is business code, smaller.(done, read react-native.js.split.build.js) - and more... - add a big game demo 2048 , can both run iOS/Android/H5 , more detail see sourcecode Both support ReactNative Android and IOS, more UI component is still in dev! We promise , we do not change any react-native core code, we only do auto translate tools! ## Have Support CSS Function - className - css unit, px , pt, em , rem - #id - .className - TagName - .className combine, like .a.b.c - .className inherit like .a .b .c ## Have Support JQuery API - $, you can use $('#id'), $('.className') to find a instance - addClass - removeClass - hasClass - css - before - append - html - offset - attr - parent, because we simulate a DOM tree - on(=addEventListener) - off(=removeEventListener) ## Have Support LocalStorage - API like web browser localstorage, example see ./reactnative/example_localstorage.js ## Have Support Animation API - requestAnimationFrame - setInterval - setTimeout ## Introduction 很高兴给大家介绍我们基于ReactNative框架实现的,目标是完全兼容现有的H5开发方式的新一代框架ReactMix, 相信大家已经使用ReactNative去开发各自的应用有一段时间了,在这段时间,因为ReactNative的API频繁变动,且文档不全,而对于已经习惯写js,css开发的前端工作者来说,ReactNative又是一种新的开发模式,现在ReactMix就是为了解决大家现在遇到的这些问题而来了。 我们通过中间层,来使得ReactNative,能支持现有的HTML5的js+ dom api + css的开发模式,完美的支持常用的 - css className - 支持了css基本单位px, pt, rem - 彻底解决了ios安卓尺寸样式不统一的问题,基于rem的度量方式,而且自适应不同的屏幕和分辨率,再也不用为未来更大屏的设备写兼容代码了 - 多个className的组合,或者className继承关系 - css选择器,支持id, className, tag选择器 - 支持Dom选择器,你可以使用#id, .className, TagName去定位和查找节点 - 支持常用的js dom event api,支持例如onclick - 支持常用的dom操作api,比如insertBefore, html等等,你经常使用的api - 支持ReactNative代码的分割打包,这样你可以把reactnative的框架代码保存在app本地,但是业务代码通过在线直连的方法更新,保证网络传输量最小 - 添加游戏2048的例子,现在启动默认进入2048,如果要修改其他例子,请修改index.ios.js的引用指向, 安卓修改index.android.js 而且我们是基于自动化脚本动态翻译的方式,使得现有的HTML+CSS+JS的代码可以无修改的直接转换成为reactnative代码,且一套不需要修改的代码,直接在iOS,andorid,winphone,H5,PC平台实现展现完全一致 ## Getting Started - 从github上下载工程,然后在根目录执行一遍npm install,再进入reactnative目录执行一遍npm install - Mac的同学,可以直接执行install.sh,功能第一条类似,分别在更目录执行npm install和在./reactnative目录执行npm install - 根目录的npm主要是用来执行css动态翻译,以及web用的js动态翻译的,./reactnaitve的npm主要用来执行reactnative - 从根目录开始,reactnative目录是主要的业务开发代码,web目录是H5相关的代码 - 我们通过代号为lightningStorm的框架代码使得reactnative支持类似html标签,和模拟css,和模拟dom api,框架地址为./reactnative/common/LightningStorm.js - 你可以打开安卓或者ios的reactnative的项目,来查看demo的例子,来了解我们的工作模式 - 我们模拟了HTML常用的多个节点,比如Div替代了reactnative的View,Span替换了reactnative的Text, Img替换了reactnative的Image,其中Div, Span, Img的用法和HTML语法的基本用法保持一致 - 主要文件说明如下: iOS入口文件还是index.ios.js,安卓同理index.android.js,但是里面只是壳子,import了框架的lightningStorm,大家都引用的index.js,这个是真正的业务入口 - H5的入口文件也是html的壳子,在./web/index.html,同理引用的是index.build.js,这个文件基于webpack.config.js打包同步自动生成的,打包文件有详细的入口是依赖和iOS同样的index.ios.js - 项目中的三个重要的打包文件一个同步翻译css到react使用的css,是react.css.build.js,基于node实现的css同步翻译脚本 - webpack.config.js是用来实现H5平台的同步翻译,把reactnative的index.ios.js同步翻译成为H5平台的业务代码 - H5和app共用一套css代码,在./css目录里面,在文件中加载css的API暂定为includeCSS - 未来会支持所有现有的CSS的功能,包括ReactNative不支持的display,甚至是伪类等等,还有media query都会计划支持到 - 目前拆出来的js文件,不包括完整的UI Component部分,UI部分计划另外开源,即时你不适用我们的ReactMix框架,你可以适用我们的UI在React或者ReactNative上面 ## Getting Help - 你可以提交issue,或者邮件我xueduanyang1985@163.com[mailto:xueduanyang1985@163.com],来反馈遇到的问题和寻求帮助 ## Documentation 第一篇原理揭秘文章在http://www.cnblogs.com/xueduanyang/p/5125781.html 系列学习文章连载中http://www.cnblogs.com/xueduanyang/p/5128690.html 更多的文档和例子正在完善中。。。 ## react-native目录主要文件介绍 这里保持和官方的reactnative代码完全一致 - css目录是存放通过根目录的react.css.build.js脚本同步编译过来的reactjs的css文件 - 保留了官方原有的index.ios.js做入口 - common目录是框架文件,以及UI组件的文件 - index.js是页面入口文件,业务逻辑 - common/LightningStorm.js是框架文件 - common/rn目录是reactnative的UI组件文件,适配与native组件 - 对应的在根目录web目录也有一个叫做common/html对应的是适配与H5的UI组件文件,和common/rn目录的API保持一致,但是不同实现 - reactnative目录增加了一些demo的例子 ## Demo 你可以发现,我们的代码基本类似现有的js+ html的开发模式 ![](http://statics1.jiaru.club/react-native-example/demo3.jpg) ![](http://statics1.jiaru.club/react-native-example/demo4.jpg) ![](http://statics1.jiaru.club/react-native-example/demo1.jpg) ![](http://statics1.jiaru.club/react-native-example/demo2.jpg) ================================================ FILE: build/part1.js ================================================ __DEV__= true; __BUNDLE_START_TIME__=Date.now(); ( function(global){ var modules=Object.create(null); var inGuard=false; function define(id,factory){ modules[id]={ factory:factory, module:{exports:{}}, isInitialized:false, hasError:false};} function require(id){ var mod=modules[id]; if(mod&&mod.isInitialized){ return mod.module.exports;} return requireImpl(id);} function requireImpl(id){ if(global.ErrorUtils&&!inGuard){ inGuard=true; var returnValue; try{ returnValue=requireImpl.apply(this,arguments);} catch(e) { global.ErrorUtils.reportFatalError(e);} inGuard=false; return returnValue;} var mod=modules[id]; if(!mod){ var msg='Requiring unknown module "'+id+'"'; if(__DEV__){ msg+='. If you are sure the module is there, try restarting the packager.';} throw new Error(msg);} if(mod.hasError){ throw new Error( 'Requiring module "'+id+'" which threw an exception');} try{ mod.isInitialized=true; __DEV__&&BridgeProfiling().profile(id); mod.factory.call(global,global,require,mod.module,mod.module.exports); __DEV__&&BridgeProfiling().profileEnd();} catch(e) { mod.hasError=true; mod.isInitialized=false; throw e;} return mod.module.exports;} var BridgeProfiling=__DEV__&&function(){ var _BridgeProfiling; try{ _BridgeProfiling=require('BridgeProfiling');} catch(e) {} return _BridgeProfiling&&_BridgeProfiling.profile? _BridgeProfiling:{profile:function(){},profileEnd:function(){}};}; global.__d=define; global.require=require;})( this); Object. assign=function(target,sources){ if(__DEV__){ if(target==null){ throw new TypeError('Object.assign target cannot be null or undefined');} if(typeof target!=='object'&&typeof target!=='function'){ throw new TypeError( 'In this environment the target of assign MUST be an object.'+ 'This error is a performance optimization and not spec compliant.');}} for(var nextIndex=1;nextIndex=0||keys.indexOf('description')>=0)){ return formatError(value);} if(keys.length===0){ if(isFunction(value)){ var name=value.name?': '+value.name:''; return ctx.stylize('[Function'+name+']','special');} if(isRegExp(value)){ return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');} if(isDate(value)){ return ctx.stylize(Date.prototype.toString.call(value),'date');} if(isError(value)){ return formatError(value);}} var base='',array=false,braces=['{','}']; if(isArray(value)){ array=true; braces=['[',']'];} if(isFunction(value)){ var n=value.name?': '+value.name:''; base=' [Function'+n+']';} if(isRegExp(value)){ base=' '+RegExp.prototype.toString.call(value);} if(isDate(value)){ base=' '+Date.prototype.toUTCString.call(value);} if(isError(value)){ base=' '+formatError(value);} if(keys.length===0&&(!array||value.length==0)){ return braces[0]+base+braces[1];} if(recurseTimes<0){ if(isRegExp(value)){ return ctx.stylize(RegExp.prototype.toString.call(value),'regexp');}else { return ctx.stylize('[Object]','special');}} ctx.seen.push(value); var output; if(array){ output=formatArray(ctx,value,recurseTimes,visibleKeys,keys);}else { output=keys.map(function(key){ return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array);});} ctx.seen.pop(); return reduceToSingleString(output,base,braces);} function formatPrimitive(ctx,value){ if(isUndefined(value)) return ctx.stylize('undefined','undefined'); if(isString(value)){ var simple='\''+JSON.stringify(value).replace(/^"|"$/g,''). replace(/'/g,"\\'"). replace(/\\"/g,'"')+'\''; return ctx.stylize(simple,'string');} if(isNumber(value)) return ctx.stylize(''+value,'number'); if(isBoolean(value)) return ctx.stylize(''+value,'boolean'); if(isNull(value)) return ctx.stylize('null','null');} function formatError(value){ return '['+Error.prototype.toString.call(value)+']';} function formatArray(ctx,value,recurseTimes,visibleKeys,keys){ var output=[]; for(var i=0,l=value.length;i-1){ if(array){ str=str.split('\n').map(function(line){ return ' '+line;}). join('\n').substr(2);}else { str='\n'+str.split('\n').map(function(line){ return ' '+line;}). join('\n');}}}else { str=ctx.stylize('[Circular]','special');}} if(isUndefined(name)){ if(array&&key.match(/^\d+$/)){ return str;} name=JSON.stringify(''+key); if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){ name=name.substr(1,name.length-2); name=ctx.stylize(name,'name');}else { name=name.replace(/'/g,"\\'"). replace(/\\"/g,'"'). replace(/(^"|"$)/g,"'"); name=ctx.stylize(name,'string');}} return name+': '+str;} function reduceToSingleString(output,base,braces){ var numLinesEst=0; var length=output.reduce(function(prev,cur){ numLinesEst++; if(cur.indexOf('\n')>=0)numLinesEst++; return prev+cur.replace(/\u001b\[\d\d?m/g,'').length+1;}, 0); if(length>60){ return braces[0]+( base===''?'':base+'\n ')+ ' '+ output.join(',\n ')+ ' '+ braces[1];} return braces[0]+base+' '+output.join(', ')+' '+braces[1];} function isArray(ar){ return Array.isArray(ar);} function isBoolean(arg){ return typeof arg==='boolean';} function isNull(arg){ return arg===null;} function isNullOrUndefined(arg){ return arg==null;} function isNumber(arg){ return typeof arg==='number';} function isString(arg){ return typeof arg==='string';} function isSymbol(arg){ return typeof arg==='symbol';} function isUndefined(arg){ return arg===void 0;} function isRegExp(re){ return isObject(re)&&objectToString(re)==='[object RegExp]';} function isObject(arg){ return typeof arg==='object'&&arg!==null;} function isDate(d){ return isObject(d)&&objectToString(d)==='[object Date]';} function isError(e){ return isObject(e)&&( objectToString(e)==='[object Error]'||e instanceof Error);} function isFunction(arg){ return typeof arg==='function';} function isPrimitive(arg){ return arg===null|| typeof arg==='boolean'|| typeof arg==='number'|| typeof arg==='string'|| typeof arg==='symbol'|| typeof arg==='undefined';} function objectToString(o){ return Object.prototype.toString.call(o);} function hasOwnProperty(obj,prop){ return Object.prototype.hasOwnProperty.call(obj,prop);} return inspect;})(); var OBJECT_COLUMN_NAME='(index)'; var LOG_LEVELS={ trace:0, info:1, warn:2, error:3}; function setupConsole(global){ var originalConsole=global.console; if(!global.nativeLoggingHook){ return;} function getNativeLogFunction(level){ return function(){ var str; if(arguments.length===1&&typeof arguments[0]==='string'){ str=arguments[0];}else { str=Array.prototype.map.call(arguments,function(arg){ return inspect(arg,{depth:10});}). join(', ');} var logLevel=level; if(str.slice(0,9)==='Warning: '&&logLevel>=LOG_LEVELS.error){ logLevel=LOG_LEVELS.warn;} global.nativeLoggingHook(str,logLevel);};} var repeat=function(element,n){ return Array.apply(null,Array(n)).map(function(){return element;});}; function consoleTablePolyfill(rows){ if(!Array.isArray(rows)){ var data=rows; rows=[]; for(var key in data){ if(data.hasOwnProperty(key)){ var row=data[key]; row[OBJECT_COLUMN_NAME]=key; rows.push(row);}}} if(rows.length===0){ global.nativeLoggingHook('',LOG_LEVELS.info); return;} var columns=Object.keys(rows[0]).sort(); var stringRows=[]; var columnWidths=[]; columns.forEach(function(k,i){ columnWidths[i]=k.length; for(var j=0;j'; function guarded(){ return ( ErrorUtils.applyWithGuard( fun, context||this, arguments, null, name));} return guarded;}}; global.ErrorUtils=ErrorUtils; function setupErrorGuard(){ var onError=function(e){ global.console.error( 'Error: '+ '\n stack: '+e.stack+ '\n line: '+e.line+ '\n message: '+e.message, e);}; global.ErrorUtils.setGlobalHandler(onError);} setupErrorGuard();})( this); if( !String.prototype.startsWith){ String.prototype.startsWith=function(search){ 'use strict'; if(this==null){ throw TypeError();} var string=String(this); var pos=arguments.length>1? Number(arguments[1])||0:0; var start=Math.min(Math.max(pos,0),string.length); return string.indexOf(String(search),pos)===start;};} if(!String.prototype.endsWith){ String.prototype.endsWith=function(search){ 'use strict'; if(this==null){ throw TypeError();} var string=String(this); var stringLength=string.length; var searchString=String(search); var pos=arguments.length>1? Number(arguments[1])||0:stringLength; var end=Math.min(Math.max(pos,0),stringLength); var start=end-searchString.length; if(start<0){ return false;} return string.lastIndexOf(searchString,start)===start;};} if(!String.prototype.contains){ String.prototype.contains=function(search){ 'use strict'; if(this==null){ throw TypeError();} var string=String(this); var pos=arguments.length>1? Number(arguments[1])||0:0; return string.indexOf(String(search),pos)!==-1;};} if(!String.prototype.repeat){ String.prototype.repeat=function(count){ 'use strict'; if(this==null){ throw TypeError();} var string=String(this); count=Number(count)||0; if(count<0||count===Infinity){ throw RangeError();} if(count===1){ return string;} var result=''; while(count){ if(count&1){ result+=string;} if(count>>=1){ string+=string;}} return result;};} ( function(undefined){ function findIndex(predicate,context){ if(this==null){ throw new TypeError( 'Array.prototype.findIndex called on null or undefined');} if(typeof predicate!=='function'){ throw new TypeError('predicate must be a function');} var list=Object(this); var length=list.length>>>0; for(var i=0;i=0)continue; if(!Object.prototype.hasOwnProperty.call(obj,i))continue; target[i]=obj[i];} return target;}; babelHelpers.possibleConstructorReturn=function(self,call){ if(!self){ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");} return call&&(typeof call==="object"||typeof call==="function")?call:self;}; babelHelpers.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");}};})(); babelHelpers.toConsumableArray=function(arr){ if(Array.isArray(arr)){ for(var i=0,arr2=Array(arr.length);i54?54:window.STYLESHEET.baseFontSize;}else { var docEl=document.documentElement, isIPhone=window.navigator.appVersion.match(/iphone/gi), fontSize,scale, platform=navigator.platform; (function recalc(){ var clientWidth=docEl.clientWidth; var dpr=window.devicePixelRatio; var justMobile=!/win32/i.test(platform); if(!(isIPhone&&justMobile)){ dpr=1;} scale=1/(dpr>1?2:dpr); fontSize=20*(clientWidth/320)/scale; fontSize=fontSize>54?54:fontSize; window.STYLESHEET.baseFontSize=fontSize; docEl.style.fontSize=fontSize+'px'; docEl.setAttribute('data-dpr',dpr); var viewport=document.querySelector('meta[name="viewport"]'); var viewport_content='initial-scale='+scale+', maximum-scale='+scale+', minimum-scale='+scale+', user-scalable=no'; viewport&&viewport.setAttribute('content',viewport_content); window.windowHeight=document.documentElement.clientHeight/scale; window.windowWidth=document.documentElement.clientWidth/scale;})();} window.upperCaseFirstLetter=function(str){ return str.replace(/^\w/,function(w){return w.toUpperCase();});}; String.prototype.toUpperCaseFirstLetter=function(){ return upperCaseFirstLetter(this);}; if(isNative){ window.Header=require('native/common/rn/Header.js'); window.RightSliderMenu=require('native/common/rn/RightSliderMenu.js'); window.Carousel=require('native/common/rn/Carousel.js');} window.$=function(selector){ if(/^#(.+)/.test(selector)){ return DOMTREE_BYID[selector.match(/^#(.+)/)[1]];}else if(/^\.(.+)/.test(selector)){ return DOMTREE_BYCLASS[selector.match(/^\.(.+)/)[1]];} return null;}; }); __d('native/common/TimerMixin.js',function(global, require, module, exports) { 'use strict'; var GLOBAL=typeof window==='undefined'?global:window; var setter=function(_setter,_clearer,array){ return function(callback,delta){ var id=_setter((function(){ _clearer.call(this,id); callback.apply(this,arguments);}). bind(this),delta); if(!this[array]){ this[array]=[id];}else { this[array].push(id);} return id;};}; var clearer=function(_clearer,array){ return function(id){ if(this[array]){ var index=this[array].indexOf(id); if(index!==-1){ this[array].splice(index,1);}} _clearer(id);};}; var _timeouts='TimerMixin_timeouts'; var _clearTimeout=clearer(GLOBAL.clearTimeout,_timeouts); var _setTimeout=setter(GLOBAL.setTimeout,_clearTimeout,_timeouts); var _intervals='TimerMixin_intervals'; var _clearInterval=clearer(GLOBAL.clearInterval,_intervals); var _setInterval=setter(GLOBAL.setInterval,function(){},_intervals); var _immediates='TimerMixin_immediates'; var _clearImmediate=clearer(GLOBAL.clearImmediate,_immediates); var _setImmediate=setter(GLOBAL.setImmediate,_clearImmediate,_immediates); var _rafs='TimerMixin_rafs'; var _cancelAnimationFrame=clearer(GLOBAL.cancelAnimationFrame,_rafs); var _requestAnimationFrame=setter(GLOBAL.requestAnimationFrame,_cancelAnimationFrame,_rafs); var TimerMixin={ componentWillUnmount:function(){ this[_timeouts]&&this[_timeouts].forEach(function(id){ GLOBAL.clearTimeout(id);}); this[_timeouts]=null; this[_intervals]&&this[_intervals].forEach(function(id){ GLOBAL.clearInterval(id);}); this[_intervals]=null; this[_immediates]&&this[_immediates].forEach(function(id){ GLOBAL.clearImmediate(id);}); this[_immediates]=null; this[_rafs]&&this[_rafs].forEach(function(id){ GLOBAL.cancelAnimationFrame(id);}); this[_rafs]=null;}, setTimeout:_setTimeout, clearTimeout:_clearTimeout, setInterval:_setInterval, clearInterval:_clearInterval, setImmediate:_setImmediate, clearImmediate:_clearImmediate, requestAnimationFrame:_requestAnimationFrame, cancelAnimationFrame:_cancelAnimationFrame}; module.exports=TimerMixin; }); __d('react-native/Libraries/react-native/react-native.js',function(global, require, module, exports) { 'use strict'; var ReactNative=babelHelpers.extends(Object.create(require('React')),{ ActivityIndicatorIOS:require('ActivityIndicatorIOS'), ART:require('ReactNativeART'), DatePickerIOS:require('DatePickerIOS'), DrawerLayoutAndroid:require('DrawerLayoutAndroid'), Image:require('Image'), ListView:require('ListView'), MapView:require('MapView'), Modal:require('Modal'), Navigator:require('Navigator'), NavigatorIOS:require('NavigatorIOS'), PickerIOS:require('PickerIOS'), ProgressBarAndroid:require('ProgressBarAndroid'), ProgressViewIOS:require('ProgressViewIOS'), ScrollView:require('ScrollView'), SegmentedControlIOS:require('SegmentedControlIOS'), SliderIOS:require('SliderIOS'), SnapshotViewIOS:require('SnapshotViewIOS'), Switch:require('Switch'), PullToRefreshViewAndroid:require('PullToRefreshViewAndroid'), SwitchAndroid:require('SwitchAndroid'), SwitchIOS:require('SwitchIOS'), TabBarIOS:require('TabBarIOS'), Text:require('Text'), TextInput:require('TextInput'), ToastAndroid:require('ToastAndroid'), ToolbarAndroid:require('ToolbarAndroid'), Touchable:require('Touchable'), TouchableHighlight:require('TouchableHighlight'), TouchableNativeFeedback:require('TouchableNativeFeedback'), TouchableOpacity:require('TouchableOpacity'), TouchableWithoutFeedback:require('TouchableWithoutFeedback'), View:require('View'), ViewPagerAndroid:require('ViewPagerAndroid'), WebView:require('WebView'), ActionSheetIOS:require('ActionSheetIOS'), AdSupportIOS:require('AdSupportIOS'), AlertIOS:require('AlertIOS'), Animated:require('Animated'), AppRegistry:require('AppRegistry'), AppStateIOS:require('AppStateIOS'), AsyncStorage:require('AsyncStorage'), BackAndroid:require('BackAndroid'), CameraRoll:require('CameraRoll'), Dimensions:require('Dimensions'), Easing:require('Easing'), ImagePickerIOS:require('ImagePickerIOS'), IntentAndroid:require('IntentAndroid'), InteractionManager:require('InteractionManager'), LayoutAnimation:require('LayoutAnimation'), LinkingIOS:require('LinkingIOS'), NetInfo:require('NetInfo'), PanResponder:require('PanResponder'), PixelRatio:require('PixelRatio'), PushNotificationIOS:require('PushNotificationIOS'), Settings:require('Settings'), StatusBarIOS:require('StatusBarIOS'), StyleSheet:require('StyleSheet'), VibrationIOS:require('VibrationIOS'), DeviceEventEmitter:require('RCTDeviceEventEmitter'), NativeAppEventEmitter:require('RCTNativeAppEventEmitter'), NativeModules:require('NativeModules'), Platform:require('Platform'), processColor:require('processColor'), requireNativeComponent:require('requireNativeComponent'), EdgeInsetsPropType:require('EdgeInsetsPropType'), PointPropType:require('PointPropType'), addons:{ LinkedStateMixin:require('LinkedStateMixin'), Perf:undefined, PureRenderMixin:require('ReactComponentWithPureRenderMixin'), TestModule:require('NativeModules').TestModule, TestUtils:undefined, batchedUpdates:require('ReactUpdates').batchedUpdates, cloneWithProps:require('cloneWithProps'), createFragment:require('ReactFragment').create, update:require('update')}}); if(__DEV__){ ReactNative.addons.Perf=require('ReactDefaultPerf'); ReactNative.addons.TestUtils=require('ReactTestUtils');} module.exports=ReactNative; }); __d('React',function(global, require, module, exports) { 'use strict'; module.exports=require('ReactNative'); }); __d('ReactNative',function(global, require, module, exports) { 'use strict'; var ReactNativeDefaultInjection=require('ReactNativeDefaultInjection'); var ReactChildren=require('ReactChildren'); var ReactClass=require('ReactClass'); var ReactComponent=require('ReactComponent'); var ReactCurrentOwner=require('ReactCurrentOwner'); var ReactElement=require('ReactElement'); var ReactElementValidator=require('ReactElementValidator'); var ReactInstanceHandles=require('ReactInstanceHandles'); var ReactNativeMount=require('ReactNativeMount'); var ReactPropTypes=require('ReactPropTypes'); var ReactUpdates=require('ReactUpdates'); var deprecated=require('deprecated'); var findNodeHandle=require('findNodeHandle'); var invariant=require('invariant'); var onlyChild=require('onlyChild'); var warning=require('warning'); ReactNativeDefaultInjection.inject(); var createElement=ReactElement.createElement; var createFactory=ReactElement.createFactory; var cloneElement=ReactElement.cloneElement; if(__DEV__){ createElement=ReactElementValidator.createElement; createFactory=ReactElementValidator.createFactory; cloneElement=ReactElementValidator.cloneElement;} var resolveDefaultProps=function(element){ var defaultProps=element.type.defaultProps; var props=element.props; for(var propName in defaultProps){ if(props[propName]===undefined){ props[propName]=defaultProps[propName];}}}; var augmentElement=function(element){ if(__DEV__){ invariant( false, 'This optimized path should never be used in DEV mode because '+ 'it does not provide validation. Check your JSX transform.');} element._owner=ReactCurrentOwner.current; if(element.type.defaultProps){ resolveDefaultProps(element);} return element;}; var render=function( element, mountInto, callback) { return ReactNativeMount.renderComponent(element,mountInto,callback);}; var ReactNative={ hasReactNativeInitialized:false, Children:{ map:ReactChildren.map, forEach:ReactChildren.forEach, count:ReactChildren.count, only:onlyChild}, Component:ReactComponent, PropTypes:ReactPropTypes, createClass:ReactClass.createClass, createElement:createElement, createFactory:createFactory, cloneElement:cloneElement, _augmentElement:augmentElement, findNodeHandle:findNodeHandle, render:render, unmountComponentAtNode:ReactNativeMount.unmountComponentAtNode, unstable_batchedUpdates:ReactUpdates.batchedUpdates, __spread:Object.assign, unmountComponentAtNodeAndRemoveContainer:ReactNativeMount.unmountComponentAtNodeAndRemoveContainer, isValidClass:ReactElement.isValidFactory, isValidElement:ReactElement.isValidElement, renderComponent:function( element, mountInto, callback) { warning('Use React.render instead of React.renderComponent'); return ReactNative.render(element,mountInto,callback);}}; if( typeof __REACT_DEVTOOLS_GLOBAL_HOOK__!=='undefined'&& typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject==='function'){ __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ CurrentOwner:ReactCurrentOwner, InstanceHandles:ReactInstanceHandles, Mount:ReactNativeMount, Reconciler:require('ReactReconciler'), TextComponent:require('ReactNativeTextComponent')});} module.exports=ReactNative; }); __d('ReactNativeDefaultInjection',function(global, require, module, exports) { 'use strict'; require('InitializeJavaScriptAppEngine'); var EventPluginHub=require('EventPluginHub'); var EventPluginUtils=require('EventPluginUtils'); var IOSDefaultEventPluginOrder=require('IOSDefaultEventPluginOrder'); var IOSNativeBridgeEventPlugin=require('IOSNativeBridgeEventPlugin'); var NodeHandle=require('NodeHandle'); var ReactComponentEnvironment=require('ReactComponentEnvironment'); var ReactDefaultBatchingStrategy=require('ReactDefaultBatchingStrategy'); var ReactEmptyComponent=require('ReactEmptyComponent'); var ReactInstanceHandles=require('ReactInstanceHandles'); var ReactNativeComponentEnvironment=require('ReactNativeComponentEnvironment'); var ReactNativeGlobalInteractionHandler=require('ReactNativeGlobalInteractionHandler'); var ReactNativeGlobalResponderHandler=require('ReactNativeGlobalResponderHandler'); var ReactNativeMount=require('ReactNativeMount'); var ReactNativeTextComponent=require('ReactNativeTextComponent'); var ReactNativeComponent=require('ReactNativeComponent'); var ReactUpdates=require('ReactUpdates'); var ResponderEventPlugin=require('ResponderEventPlugin'); var UniversalWorkerNodeHandle=require('UniversalWorkerNodeHandle'); var createReactNativeComponentClass=require('createReactNativeComponentClass'); var invariant=require('invariant'); require('RCTEventEmitter'); require('RCTLog'); require('JSTimersExecution'); function inject(){ EventPluginHub.injection.injectEventPluginOrder(IOSDefaultEventPluginOrder); EventPluginHub.injection.injectInstanceHandle(ReactInstanceHandles); ResponderEventPlugin.injection.injectGlobalResponderHandler( ReactNativeGlobalResponderHandler); ResponderEventPlugin.injection.injectGlobalInteractionHandler( ReactNativeGlobalInteractionHandler); EventPluginHub.injection.injectEventPluginsByName({ 'ResponderEventPlugin':ResponderEventPlugin, 'IOSNativeBridgeEventPlugin':IOSNativeBridgeEventPlugin}); ReactUpdates.injection.injectReconcileTransaction( ReactNativeComponentEnvironment.ReactReconcileTransaction); ReactUpdates.injection.injectBatchingStrategy( ReactDefaultBatchingStrategy); ReactComponentEnvironment.injection.injectEnvironment( ReactNativeComponentEnvironment); var RCTView=createReactNativeComponentClass({ validAttributes:{}, uiViewClassName:'RCTView'}); ReactEmptyComponent.injection.injectEmptyComponent(RCTView); EventPluginUtils.injection.injectMount(ReactNativeMount); ReactNativeComponent.injection.injectTextComponentClass( ReactNativeTextComponent); ReactNativeComponent.injection.injectGenericComponentClass(function(tag){ var info=''; if(typeof tag==='string'&&/^[a-z]/.test(tag)){ info+=' Each component name should start with an uppercase letter.';} invariant(false,'Expected a component class, got %s.%s',tag,info);}); NodeHandle.injection.injectImplementation(UniversalWorkerNodeHandle);} module.exports={ inject:inject}; }); __d('InitializeJavaScriptAppEngine',function(global, require, module, exports) { require( 'regenerator/runtime.js'); if(typeof GLOBAL==='undefined'){ GLOBAL=this;} if(typeof window==='undefined'){ window=GLOBAL;} function setUpConsole(){ var ExceptionsManager=require('ExceptionsManager'); ExceptionsManager.installConsoleErrorReporter();} function polyfillGlobal(name,newValue){var scope=arguments.length<=2||arguments[2]===undefined?GLOBAL:arguments[2]; var descriptor=Object.getOwnPropertyDescriptor(scope,name)||{ writable:true}; if(scope[name]!==undefined){ var backupName='original'+name[0].toUpperCase()+name.substr(1); Object.defineProperty(scope,backupName,babelHelpers.extends({},descriptor,{value:scope[name]}));} Object.defineProperty(scope,name,babelHelpers.extends({},descriptor,{value:newValue}));} function setUpErrorHandler(){ if(global.__fbDisableExceptionsManager){ return;} function handleError(e,isFatal){ try{ require('ExceptionsManager').handleException(e,isFatal);} catch(ee) { console.log('Failed to print error: ',ee.message);}} var ErrorUtils=require('ErrorUtils'); ErrorUtils.setGlobalHandler(handleError);} function setUpFlowChecker(){ if(__DEV__){ var checkFlowAtRuntime=require('checkFlowAtRuntime'); checkFlowAtRuntime();}} function setUpTimers(){ var JSTimers=require('JSTimers'); GLOBAL.setTimeout=JSTimers.setTimeout; GLOBAL.setInterval=JSTimers.setInterval; GLOBAL.setImmediate=JSTimers.setImmediate; GLOBAL.clearTimeout=JSTimers.clearTimeout; GLOBAL.clearInterval=JSTimers.clearInterval; GLOBAL.clearImmediate=JSTimers.clearImmediate; GLOBAL.cancelAnimationFrame=JSTimers.clearInterval; GLOBAL.requestAnimationFrame=function(cb){ return JSTimers.requestAnimationFrame(cb);};} function setUpAlert(){ var RCTAlertManager=require('NativeModules').AlertManager; if(!GLOBAL.alert){ GLOBAL.alert=function(text){ var alertOpts={ title:'Alert', message:''+text, buttons:[{'cancel':'OK'}]}; RCTAlertManager.alertWithArgs(alertOpts,function(){});};}} function setUpPromise(){ GLOBAL.Promise=require('Promise');} function setUpXHR(){ polyfillGlobal('XMLHttpRequest',require('XMLHttpRequest')); polyfillGlobal('FormData',require('FormData')); var fetchPolyfill=require('fetch'); polyfillGlobal('fetch',fetchPolyfill.fetch); polyfillGlobal('Headers',fetchPolyfill.Headers); polyfillGlobal('Request',fetchPolyfill.Request); polyfillGlobal('Response',fetchPolyfill.Response);} function setUpGeolocation(){ GLOBAL.navigator=GLOBAL.navigator||{}; polyfillGlobal('geolocation',require('Geolocation'),GLOBAL.navigator);} function setUpWebSockets(){ polyfillGlobal('WebSocket',require('WebSocket'));} function setUpProfile(){ if(__DEV__){ var BridgeProfiling=require('BridgeProfiling'); BridgeProfiling.swizzleReactPerf(); BridgeProfiling.attachToRelayProfiler();}} function setUpProcessEnv(){ GLOBAL.process=GLOBAL.process||{}; GLOBAL.process.env=GLOBAL.process.env||{}; if(!GLOBAL.process.env.NODE_ENV){ GLOBAL.process.env.NODE_ENV=__DEV__?'development':'production';}} function setUpNumber(){ Number.EPSILON=Number.EPSILON||Math.pow(2,-52); Number.MAX_SAFE_INTEGER=Number.MAX_SAFE_INTEGER||Math.pow(2,53)-1; Number.MIN_SAFE_INTEGER=Number.MIN_SAFE_INTEGER||-(Math.pow(2,53)-1);} function setUpDevTools(){ if(__DEV__){ if(!window.document&&require('Platform').OS==='ios'){ var setupDevtools=require('setupDevtools'); setupDevtools();}}} setUpProcessEnv(); setUpConsole(); setUpTimers(); setUpAlert(); setUpPromise(); setUpErrorHandler(); setUpXHR(); setUpGeolocation(); setUpWebSockets(); setUpProfile(); setUpFlowChecker(); setUpNumber(); setUpDevTools(); if(__DEV__){ require('RCTDebugComponentOwnership');} require('RCTDeviceEventEmitter'); require('PerformanceLogger'); }); __d('regenerator/runtime.js',function(global, require, module, exports) { ! (function(global){ "use strict"; var hasOwn=Object.prototype.hasOwnProperty; var undefined; var $Symbol=typeof Symbol==="function"?Symbol:{}; var iteratorSymbol=$Symbol.iterator||"@@iterator"; var toStringTagSymbol=$Symbol.toStringTag||"@@toStringTag"; var inModule=typeof module==="object"; var runtime=global.regeneratorRuntime; if(runtime){ if(inModule){ module.exports=runtime;} return;} runtime=global.regeneratorRuntime=inModule?module.exports:{}; function wrap(innerFn,outerFn,self,tryLocsList){ var generator=Object.create((outerFn||Generator).prototype); var context=new Context(tryLocsList||[]); generator._invoke=makeInvokeMethod(innerFn,self,context); return generator;} runtime.wrap=wrap; function tryCatch(fn,obj,arg){ try{ return {type:"normal",arg:fn.call(obj,arg)};} catch(err) { return {type:"throw",arg:err};}} var GenStateSuspendedStart="suspendedStart"; var GenStateSuspendedYield="suspendedYield"; var GenStateExecuting="executing"; var GenStateCompleted="completed"; var ContinueSentinel={}; function Generator(){} function GeneratorFunction(){} function GeneratorFunctionPrototype(){} var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype; GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor=GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol]=GeneratorFunction.displayName="GeneratorFunction"; function defineIteratorMethods(prototype){ ["next","throw","return"].forEach(function(method){ prototype[method]=function(arg){ return this._invoke(method,arg);};});} runtime.isGeneratorFunction=function(genFun){ var ctor=typeof genFun==="function"&&genFun.constructor; return ctor? ctor===GeneratorFunction|| (ctor.displayName||ctor.name)==="GeneratorFunction": false;}; runtime.mark=function(genFun){ if(Object.setPrototypeOf){ Object.setPrototypeOf(genFun,GeneratorFunctionPrototype);}else { genFun.__proto__=GeneratorFunctionPrototype; if(!(toStringTagSymbol in genFun)){ genFun[toStringTagSymbol]="GeneratorFunction";}} genFun.prototype=Object.create(Gp); return genFun;}; runtime.awrap=function(arg){ return new AwaitArgument(arg);}; function AwaitArgument(arg){ this.arg=arg;} function AsyncIterator(generator){ function invoke(method,arg,resolve,reject){ var record=tryCatch(generator[method],generator,arg); if(record.type==="throw"){ reject(record.arg);}else { var result=record.arg; var value=result.value; if(value instanceof AwaitArgument){ return Promise.resolve(value.arg).then(function(value){ invoke("next",value,resolve,reject);}, function(err){ invoke("throw",err,resolve,reject);});} return Promise.resolve(value).then(function(unwrapped){ result.value=unwrapped; resolve(result);}, reject);}} if(typeof process==="object"&&process.domain){ invoke=process.domain.bind(invoke);} var previousPromise; function enqueue(method,arg){ function callInvokeWithMethodAndArg(){ return new Promise(function(resolve,reject){ invoke(method,arg,resolve,reject);});} return previousPromise= previousPromise?previousPromise.then( callInvokeWithMethodAndArg, callInvokeWithMethodAndArg): callInvokeWithMethodAndArg();} this._invoke=enqueue;} defineIteratorMethods(AsyncIterator.prototype); runtime.async=function(innerFn,outerFn,self,tryLocsList){ var iter=new AsyncIterator( wrap(innerFn,outerFn,self,tryLocsList)); return runtime.isGeneratorFunction(outerFn)? iter: iter.next().then(function(result){ return result.done?result.value:iter.next();});}; function makeInvokeMethod(innerFn,self,context){ var state=GenStateSuspendedStart; return function invoke(method,arg){ if(state===GenStateExecuting){ throw new Error("Generator is already running");} if(state===GenStateCompleted){ if(method==="throw"){ throw arg;} return doneResult();} while(true){ var delegate=context.delegate; if(delegate){ if(method==="return"|| method==="throw"&&delegate.iterator[method]===undefined){ context.delegate=null; var returnMethod=delegate.iterator["return"]; if(returnMethod){ var record=tryCatch(returnMethod,delegate.iterator,arg); if(record.type==="throw"){ method="throw"; arg=record.arg; continue;}} if(method==="return"){ continue;}} var record=tryCatch( delegate.iterator[method], delegate.iterator, arg); if(record.type==="throw"){ context.delegate=null; method="throw"; arg=record.arg; continue;} method="next"; arg=undefined; var info=record.arg; if(info.done){ context[delegate.resultName]=info.value; context.next=delegate.nextLoc;}else { state=GenStateSuspendedYield; return info;} context.delegate=null;} if(method==="next"){ if(state===GenStateSuspendedYield){ context.sent=arg;}else { context.sent=undefined;}}else if(method==="throw"){ if(state===GenStateSuspendedStart){ state=GenStateCompleted; throw arg;} if(context.dispatchException(arg)){ method="next"; arg=undefined;}}else if(method==="return"){ context.abrupt("return",arg);} state=GenStateExecuting; var record=tryCatch(innerFn,self,context); if(record.type==="normal"){ state=context.done? GenStateCompleted: GenStateSuspendedYield; var info={ value:record.arg, done:context.done}; if(record.arg===ContinueSentinel){ if(context.delegate&&method==="next"){ arg=undefined;}}else { return info;}}else if(record.type==="throw"){ state=GenStateCompleted; method="throw"; arg=record.arg;}}};} defineIteratorMethods(Gp); Gp[iteratorSymbol]=function(){ return this;}; Gp[toStringTagSymbol]="Generator"; Gp.toString=function(){ return "[object Generator]";}; function pushTryEntry(locs){ var entry={tryLoc:locs[0]}; if(1 in locs){ entry.catchLoc=locs[1];} if(2 in locs){ entry.finallyLoc=locs[2]; entry.afterLoc=locs[3];} this.tryEntries.push(entry);} function resetTryEntry(entry){ var record=entry.completion||{}; record.type="normal"; delete record.arg; entry.completion=record;} function Context(tryLocsList){ this.tryEntries=[{tryLoc:"root"}]; tryLocsList.forEach(pushTryEntry,this); this.reset(true);} runtime.keys=function(object){ var keys=[]; for(var key in object){ keys.push(key);} keys.reverse(); return function next(){ while(keys.length){ var key=keys.pop(); if(key in object){ next.value=key; next.done=false; return next;}} next.done=true; return next;};}; function values(iterable){ if(iterable){ var iteratorMethod=iterable[iteratorSymbol]; if(iteratorMethod){ return iteratorMethod.call(iterable);} if(typeof iterable.next==="function"){ return iterable;} if(!isNaN(iterable.length)){ var i=-1,next=function next(){ while(++i=0;--i){ var entry=this.tryEntries[i]; var record=entry.completion; if(entry.tryLoc==="root"){ return handle("end");} if(entry.tryLoc<=this.prev){ var hasCatch=hasOwn.call(entry,"catchLoc"); var hasFinally=hasOwn.call(entry,"finallyLoc"); if(hasCatch&&hasFinally){ if(this.prev=0;--i){ var entry=this.tryEntries[i]; if(entry.tryLoc<=this.prev&& hasOwn.call(entry,"finallyLoc")&& this.prev=0;--i){ var entry=this.tryEntries[i]; if(entry.finallyLoc===finallyLoc){ this.complete(entry.completion,entry.afterLoc); resetTryEntry(entry); return ContinueSentinel;}}}, "catch":function(tryLoc){ for(var i=this.tryEntries.length-1;i>=0;--i){ var entry=this.tryEntries[i]; if(entry.tryLoc===tryLoc){ var record=entry.completion; if(record.type==="throw"){ var thrown=record.arg; resetTryEntry(entry);} return thrown;}} throw new Error("illegal catch attempt");}, delegateYield:function(iterable,resultName,nextLoc){ this.delegate={ iterator:values(iterable), resultName:resultName, nextLoc:nextLoc}; return ContinueSentinel;}};})( typeof global==="object"?global: typeof window==="object"?window: typeof self==="object"?self:this); }); __d('ExceptionsManager',function(global, require, module, exports) { 'use strict'; var RCTExceptionsManager=require('NativeModules').ExceptionsManager; var loadSourceMap=require('loadSourceMap'); var parseErrorStack=require('parseErrorStack'); var stringifySafe=require('stringifySafe'); var sourceMapPromise; var exceptionID=0; function reportException(e,isFatal){ var currentExceptionID=++exceptionID; if(RCTExceptionsManager){ var stack=parseErrorStack(e); if(isFatal){ RCTExceptionsManager.reportFatalException(e.message,stack,currentExceptionID);}else { RCTExceptionsManager.reportSoftException(e.message,stack,currentExceptionID);} if(__DEV__){ (sourceMapPromise=sourceMapPromise||loadSourceMap()). then(function(map){ var prettyStack=parseErrorStack(e,map); RCTExceptionsManager.updateExceptionMessage(e.message,prettyStack,currentExceptionID);}). catch(function(error){ console.warn('Unable to load source map: '+error.message);});}}} function handleException(e,isFatal){ if(!e.message){ e=new Error(e);} (console._errorOriginal||console.error)(e.message); reportException(e,isFatal);} function installConsoleErrorReporter(){ if(console._errorOriginal){ return;} console._errorOriginal=console.error.bind(console); console.error=function reactConsoleError(){ console._errorOriginal.apply(null,arguments); if(!console.reportErrorsAsExceptions){ return;} if(arguments[0]&&arguments[0].stack){ reportException(arguments[0],false);}else { var str=Array.prototype.map.call(arguments,stringifySafe).join(', '); if(str.slice(0,10)==='"Warning: '){ return;} var error=new Error('console.error: '+str); error.framesToPop=1; reportException(error,false);}}; if(console.reportErrorsAsExceptions===undefined){ console.reportErrorsAsExceptions=true;}} module.exports={handleException:handleException,installConsoleErrorReporter:installConsoleErrorReporter}; }); __d('NativeModules',function(global, require, module, exports) { 'use strict'; var NativeModules=require('BatchedBridge').RemoteModules; var nativeModulePrefixNormalizer=require('nativeModulePrefixNormalizer'); nativeModulePrefixNormalizer(NativeModules); module.exports=NativeModules; }); __d('BatchedBridge',function(global, require, module, exports) { 'use strict'; var MessageQueue=require('MessageQueue'); var BatchedBridge=new MessageQueue( __fbBatchedBridgeConfig.remoteModuleConfig, __fbBatchedBridgeConfig.localModulesConfig); module.exports=BatchedBridge; }); __d('MessageQueue',function(global, require, module, exports) { 'use strict'; var BridgeProfiling=require('BridgeProfiling'); var ErrorUtils=require('ErrorUtils'); var JSTimersExecution=require('JSTimersExecution'); var ReactUpdates=require('ReactUpdates'); var invariant=require('invariant'); var keyMirror=require('keyMirror'); var stringifySafe=require('stringifySafe'); var MODULE_IDS=0; var METHOD_IDS=1; var PARAMS=2; var MIN_TIME_BETWEEN_FLUSHES_MS=5; var SPY_MODE=false; var MethodTypes=keyMirror({ remote:null, remoteAsync:null}); var guard=function(fn){ try{ fn();} catch(error) { ErrorUtils.reportFatalError(error);}};var MessageQueue=(function(){ function MessageQueue(remoteModules,localModules,customRequire){var _this=this;babelHelpers.classCallCheck(this,MessageQueue); this.RemoteModules={}; this._require=customRequire||require; this._queue=[[],[],[]]; this._moduleTable={}; this._methodTable={}; this._callbacks=[]; this._callbackID=0; this._lastFlush=0; [ 'invokeCallbackAndReturnFlushedQueue', 'callFunctionReturnFlushedQueue', 'flushedQueue']. forEach(function(fn){return _this[fn]=_this[fn].bind(_this);}); var modulesConfig=this._genModulesConfig(remoteModules); this._genModules(modulesConfig); localModules&&this._genLookupTables( this._genModulesConfig(localModules),this._moduleTable,this._methodTable); this._copyNativeComponentConstants(this.RemoteModules); this._debugInfo={}; this._remoteModuleTable={}; this._remoteMethodTable={}; this._genLookupTables( modulesConfig,this._remoteModuleTable,this._remoteMethodTable);}babelHelpers.createClass(MessageQueue,[{key:'callFunctionReturnFlushedQueue',value:function callFunctionReturnFlushedQueue( module,method,args){var _this2=this; guard(function(){ _this2.__callFunction(module,method,args); _this2.__callImmediates();}); return this.flushedQueue();}},{key:'invokeCallbackAndReturnFlushedQueue',value:function invokeCallbackAndReturnFlushedQueue( cbID,args){var _this3=this; guard(function(){ _this3.__invokeCallback(cbID,args); _this3.__callImmediates();}); return this.flushedQueue();}},{key:'flushedQueue',value:function flushedQueue() { this.__callImmediates(); var queue=this._queue; this._queue=[[],[],[]]; return queue[0].length?queue:null;}},{key:'__callImmediates',value:function __callImmediates() { BridgeProfiling.profile('JSTimersExecution.callImmediates()'); guard(function(){return JSTimersExecution.callImmediates();}); BridgeProfiling.profileEnd();}},{key:'__nativeCall',value:function __nativeCall( module,method,params,onFail,onSucc){ if(onFail||onSucc){ this._callbackID>1<<5&&( this._debugInfo[this._callbackID>>5]=null); this._debugInfo[this._callbackID>>1]=[module,method]; onFail&¶ms.push(this._callbackID); this._callbacks[this._callbackID++]=onFail; onSucc&¶ms.push(this._callbackID); this._callbacks[this._callbackID++]=onSucc;} this._queue[MODULE_IDS].push(module); this._queue[METHOD_IDS].push(method); this._queue[PARAMS].push(params); var now=new Date().getTime(); if(global.nativeFlushQueueImmediate&& now-this._lastFlush>=MIN_TIME_BETWEEN_FLUSHES_MS){ global.nativeFlushQueueImmediate(this._queue); this._queue=[[],[],[]]; this._lastFlush=now;} if(__DEV__&&SPY_MODE&&isFinite(module)){ console.log('JS->N : '+this._remoteModuleTable[module]+'.'+ this._remoteMethodTable[module][method]+'('+JSON.stringify(params)+')');}}},{key:'__callFunction',value:function __callFunction( module,method,args){ BridgeProfiling.profile(function(){return module+'.'+method+'('+stringifySafe(args)+')';}); this._lastFlush=new Date().getTime(); if(isFinite(module)){ method=this._methodTable[module][method]; module=this._moduleTable[module];} if(__DEV__&&SPY_MODE){ console.log('N->JS : '+module+'.'+method+'('+JSON.stringify(args)+')');} module=this._require(module); module[method].apply(module,args); BridgeProfiling.profileEnd();}},{key:'__invokeCallback',value:function __invokeCallback( cbID,args){ BridgeProfiling.profile( function(){return 'MessageQueue.invokeCallback('+cbID+', '+stringifySafe(args)+')';}); this._lastFlush=new Date().getTime(); var callback=this._callbacks[cbID]; if(!callback||__DEV__){ var debug=this._debugInfo[cbID>>1]; var _module=debug&&this._remoteModuleTable[debug[0]]; var method=debug&&this._remoteMethodTable[debug[0]][debug[1]]; invariant( callback,'Callback with id '+ cbID+': '+_module+'.'+method+'() not found'); if(callback&&SPY_MODE){ console.log('N->JS : ('+JSON.stringify(args)+')');}} this._callbacks[cbID&~1]=null; this._callbacks[cbID|1]=null; callback.apply(null,args); BridgeProfiling.profileEnd();}},{key:'_copyNativeComponentConstants',value:function _copyNativeComponentConstants( remoteModules){ var UIManager=remoteModules.RCTUIManager; UIManager&&Object.keys(UIManager).forEach(function(viewName){ var viewConfig=UIManager[viewName]; if(viewConfig.Manager){(function(){ var viewManager=remoteModules[viewConfig.Manager]; viewManager&&Object.keys(viewManager).forEach(function(key){ var value=viewManager[key]; if(typeof value!=='function'){ if(!viewConfig.Constants){ viewConfig.Constants={};} viewConfig.Constants[key]=value;}});})();}});}},{key:'_genModulesConfig',value:function _genModulesConfig( modules){ if(Array.isArray(modules)){ return modules;}else { var moduleArray=[]; var moduleNames=Object.keys(modules); for(var i=0,l=moduleNames.length;i0?args[args.length-1]:null; var secondLastArg=args.length>1?args[args.length-2]:null; var hasSuccCB=typeof lastArg==='function'; var hasErrorCB=typeof secondLastArg==='function'; hasErrorCB&&invariant( hasSuccCB, 'Cannot have a non-function arg after a function arg.'); var numCBs=hasSuccCB+hasErrorCB; var onSucc=hasSuccCB?lastArg:null; var onFail=hasErrorCB?secondLastArg:null; args=args.slice(0,args.length-numCBs); return self.__nativeCall(module,method,args,onFail,onSucc);};} fn.type=type; return fn;}}]);return MessageQueue;})(); function moduleHasConstants(moduleArray){ return !Array.isArray(moduleArray[1]);} function arrayContains(array,value){ return array.indexOf(value)!==-1;} function createErrorFromErrorData(errorData){var message= errorData.message;var extraErrorInfo=babelHelpers.objectWithoutProperties(errorData,['message']); var error=new Error(message); error.framesToPop=1; return babelHelpers.extends(error,extraErrorInfo);} module.exports=MessageQueue; }); __d('BridgeProfiling',function(global, require, module, exports) { 'use strict'; var GLOBAL=GLOBAL||this; var TRACE_TAG_REACT_APPS=1<<17; var _enabled; var _ReactPerf=null; function ReactPerf(){ if(!_ReactPerf){ _ReactPerf=require('ReactPerf');} return _ReactPerf;} var BridgeProfiling={ setEnabled:function(enabled){ _enabled=enabled; ReactPerf().enableMeasure=enabled;}, profile:function(profileName){ if(_enabled){ profileName=typeof profileName==='function'? profileName():profileName; global.nativeTraceBeginSection(TRACE_TAG_REACT_APPS,profileName);}}, profileEnd:function(){ if(_enabled){ global.nativeTraceEndSection(TRACE_TAG_REACT_APPS);}}, reactPerfMeasure:function(objName,fnName,func){ return function(component){ if(!_enabled){ return func.apply(this,arguments);} var name=objName==='ReactCompositeComponent'&&this.getName()||''; BridgeProfiling.profile(objName+'.'+fnName+'('+name+')'); var ret=func.apply(this,arguments); BridgeProfiling.profileEnd(); return ret;};}, swizzleReactPerf:function(){ ReactPerf().injection.injectMeasure(BridgeProfiling.reactPerfMeasure);}, attachToRelayProfiler:function(){ try{ var rpName='RelayProfiler'; var RelayProfiler=require(rpName); RelayProfiler.attachProfileHandler('*',function(name){ BridgeProfiling.profile(name); return function(){ BridgeProfiling.profileEnd();};});} catch(err) {}}, swizzleJSON:function(){ BridgeProfiling.measureMethods(JSON,'JSON',[ 'parse', 'stringify']);}, measureMethods:function(object,objectName,methodNames){ if(!__DEV__){ return;} methodNames.forEach(function(methodName){ object[methodName]=BridgeProfiling.measure( objectName, methodName, object[methodName]);});}, measure:function(objName,fnName,func){ if(!__DEV__){ return func;} var profileName=objName+'.'+fnName; return function(){ if(!_enabled){ return func.apply(this,arguments);} BridgeProfiling.profile(profileName); var ret=func.apply(this,arguments); BridgeProfiling.profileEnd(); return ret;};}}; BridgeProfiling.setEnabled(global.__RCTProfileIsProfiling||false); module.exports=BridgeProfiling; }); __d('ReactPerf',function(global, require, module, exports) { 'use strict'; var ReactPerf={ enableMeasure:false, storedMeasure:_noMeasure, measureMethods:function(object,objectName,methodNames){ if(__DEV__){ for(var key in methodNames){ if(!methodNames.hasOwnProperty(key)){ continue;} object[key]=ReactPerf.measure( objectName, methodNames[key], object[key]);}}}, measure:function(objName,fnName,func){ if(__DEV__){ 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:{ injectMeasure:function(measure){ ReactPerf.storedMeasure=measure;}}}; function _noMeasure(objName,fnName,func){ return func;} module.exports=ReactPerf; }); __d('ErrorUtils',function(global, require, module, exports) { var GLOBAL=this; module.exports=GLOBAL.ErrorUtils; }); __d('JSTimersExecution',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var keyMirror=require('keyMirror'); var performanceNow=require('performanceNow'); var warning=require('warning'); var BridgeProfiling=require('BridgeProfiling'); var JSTimersExecution={ GUID:1, Type:keyMirror({ setTimeout:null, setInterval:null, requestAnimationFrame:null, setImmediate:null}), callbacks:[], types:[], timerIDs:[], immediates:[], callTimer:function(timerID){ warning(timerID<=JSTimersExecution.GUID,'Tried to call timer with ID '+timerID+' but no such timer exists'); var timerIndex=JSTimersExecution.timerIDs.indexOf(timerID); if(timerIndex===-1){ return;} var type=JSTimersExecution.types[timerIndex]; var callback=JSTimersExecution.callbacks[timerIndex]; if(type===JSTimersExecution.Type.setTimeout|| type===JSTimersExecution.Type.setImmediate|| type===JSTimersExecution.Type.requestAnimationFrame){ JSTimersExecution._clearIndex(timerIndex);} try{ if(type===JSTimersExecution.Type.setTimeout|| type===JSTimersExecution.Type.setInterval|| type===JSTimersExecution.Type.setImmediate){ callback();}else if(type===JSTimersExecution.Type.requestAnimationFrame){ var currentTime=performanceNow(); callback(currentTime);}else { console.error('Tried to call a callback with invalid type: '+type); return;}} catch(e) { JSTimersExecution.errors=JSTimersExecution.errors||[]; JSTimersExecution.errors.push(e);}}, callTimers:function(timerIDs){ invariant(timerIDs.length!==0,'Probably shouldn\'t call "callTimers" with no timerIDs'); JSTimersExecution.errors=null; timerIDs.forEach(JSTimersExecution.callTimer); var errors=JSTimersExecution.errors; if(errors){ var errorCount=errors.length; if(errorCount>1){ for(var ii=1;ii0){ var passImmediates=JSTimersExecution.immediates.slice(); JSTimersExecution.immediates=[]; passImmediates.forEach(function(timerID){ JSTimersExecution.callTimer(timerID);});} BridgeProfiling.profileEnd(); return JSTimersExecution.immediates.length>0;}, callImmediates:function(){ JSTimersExecution.errors=null; while(JSTimersExecution.callImmediatesPass()){} if(JSTimersExecution.errors){ JSTimersExecution.errors.forEach(function(error){return ( require('JSTimers').setTimeout(function(){throw error;},0));});}}, _clearIndex:function(i){ JSTimersExecution.timerIDs[i]=null; JSTimersExecution.callbacks[i]=null; JSTimersExecution.types[i]=null;}}; module.exports=JSTimersExecution; }); __d('invariant',function(global, require, module, exports) { 'use strict'; var invariant=function(condition,format,a,b,c,d,e,f){ if(__DEV__){ if(format===undefined){ throw new Error('invariant requires an error message argument');}} if(!condition){ var error; if(format===undefined){ error=new Error( 'Minified exception occurred; use the non-minified dev environment '+ 'for the full error message and additional helpful warnings.');}else { var args=[a,b,c,d,e,f]; var argIndex=0; error=new Error( 'Invariant Violation: '+ format.replace(/%s/g,function(){return args[argIndex++];}));} error.framesToPop=1; throw error;}}; module.exports=invariant; }); __d('keyMirror',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var keyMirror=function(obj){ var ret={}; var key; invariant( obj instanceof Object&&!Array.isArray(obj), 'keyMirror(...): Argument must be an object.'); for(key in obj){ if(!obj.hasOwnProperty(key)){ continue;} ret[key]=key;} return ret;}; module.exports=keyMirror; }); __d('performanceNow',function(global, require, module, exports) { var performance=require('performance'); var curPerformance=performance; if(!curPerformance||!curPerformance.now){ curPerformance=Date;} var performanceNow=curPerformance.now.bind(curPerformance); module.exports=performanceNow; }); __d('performance',function(global, require, module, exports) { 'use strict'; var ExecutionEnvironment=require('ExecutionEnvironment'); var performance; if(ExecutionEnvironment.canUseDOM){ performance= window.performance|| window.msPerformance|| window.webkitPerformance;} module.exports=performance||{}; }); __d('ExecutionEnvironment',function(global, require, module, exports) { "use strict"; var canUseDOM=false; var ExecutionEnvironment={ canUseDOM:canUseDOM, canUseWorkers:typeof Worker!=='undefined', canUseEventListeners: canUseDOM&&!!(window.addEventListener||window.attachEvent), canUseViewport:canUseDOM&&!!window.screen, isInWorker:!canUseDOM}; module.exports=ExecutionEnvironment; }); __d('warning',function(global, require, module, exports) { 'use strict'; var emptyFunction=require('emptyFunction'); var warning=emptyFunction; if(__DEV__){ 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;} if(!condition){ var argIndex=0; var message='Warning: '+format.replace(/%s/g,function(){return args[argIndex++];}); if(typeof console!=='undefined'){ console.error(message);} try{ throw new Error(message);} catch(x) {}}};} module.exports=warning; }); __d('emptyFunction',function(global, require, module, exports) { function makeEmptyFunction(arg){ return function(){ return arg;};} 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; }); __d('JSTimers',function(global, require, module, exports) { 'use strict'; var RCTTiming=require('NativeModules').Timing; var JSTimersExecution=require('JSTimersExecution'); var JSTimers={ Types:JSTimersExecution.Types, _getFreeIndex:function(){ var freeIndex=JSTimersExecution.timerIDs.indexOf(null); if(freeIndex===-1){ freeIndex=JSTimersExecution.timerIDs.length;} return freeIndex;}, setTimeout:function(func,duration){for(var _len=arguments.length,args=Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];} var newID=JSTimersExecution.GUID++; var freeIndex=JSTimers._getFreeIndex(); JSTimersExecution.timerIDs[freeIndex]=newID; JSTimersExecution.callbacks[freeIndex]=function(){ return func.apply(undefined,args);}; JSTimersExecution.types[freeIndex]=JSTimersExecution.Type.setTimeout; RCTTiming.createTimer(newID,duration||0,Date.now(),false); return newID;}, setInterval:function(func,duration){for(var _len2=arguments.length,args=Array(_len2>2?_len2-2:0),_key2=2;_key2<_len2;_key2++){args[_key2-2]=arguments[_key2];} var newID=JSTimersExecution.GUID++; var freeIndex=JSTimers._getFreeIndex(); JSTimersExecution.timerIDs[freeIndex]=newID; JSTimersExecution.callbacks[freeIndex]=function(){ return func.apply(undefined,args);}; JSTimersExecution.types[freeIndex]=JSTimersExecution.Type.setInterval; RCTTiming.createTimer(newID,duration||0,Date.now(),true); return newID;}, setImmediate:function(func){for(var _len3=arguments.length,args=Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];} var newID=JSTimersExecution.GUID++; var freeIndex=JSTimers._getFreeIndex(); JSTimersExecution.timerIDs[freeIndex]=newID; JSTimersExecution.callbacks[freeIndex]=function(){ return func.apply(undefined,args);}; JSTimersExecution.types[freeIndex]=JSTimersExecution.Type.setImmediate; JSTimersExecution.immediates.push(newID); return newID;}, requestAnimationFrame:function(func){ var newID=JSTimersExecution.GUID++; var freeIndex=JSTimers._getFreeIndex(); JSTimersExecution.timerIDs[freeIndex]=newID; JSTimersExecution.callbacks[freeIndex]=func; JSTimersExecution.types[freeIndex]=JSTimersExecution.Type.requestAnimationFrame; RCTTiming.createTimer(newID,1,Date.now(),false); return newID;}, clearTimeout:function(timerID){ JSTimers._clearTimerID(timerID);}, clearInterval:function(timerID){ JSTimers._clearTimerID(timerID);}, clearImmediate:function(timerID){ JSTimers._clearTimerID(timerID); JSTimersExecution.immediates.splice( JSTimersExecution.immediates.indexOf(timerID), 1);}, cancelAnimationFrame:function(timerID){ JSTimers._clearTimerID(timerID);}, _clearTimerID:function(timerID){ if(timerID==null){ return;} var index=JSTimersExecution.timerIDs.indexOf(timerID); if(index!==-1){ JSTimersExecution._clearIndex(index); if(JSTimersExecution.types[index]!==JSTimersExecution.Type.setImmediate){ RCTTiming.deleteTimer(timerID);}}}}; module.exports=JSTimers; }); __d('ReactUpdates',function(global, require, module, exports) { '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('invariant'); var dirtyComponents=[]; var asapCallbackQueue=CallbackQueue.getPooled(); var asapEnqueued=false; var batchingStrategy=null; function ensureInjected(){ invariant( ReactUpdates.ReactReconcileTransaction&&batchingStrategy, 'ReactUpdates: must inject a reconcile transaction class and batching '+ 'strategy');} var NESTED_UPDATES={ initialize:function(){ this.dirtyComponentsLength=dirtyComponents.length;}, close:function(){ if(this.dirtyComponentsLength!==dirtyComponents.length){ 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(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){ 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);} function mountOrderComparator(c1,c2){ return c1._mountOrder-c2._mountOrder;} function runBatchedUpdates(transaction){ var len=transaction.dirtyComponentsLength; invariant( len===dirtyComponents.length, 'Expected flush transaction\'s stored dirty-components length (%s) to '+ 'match dirty-components array length (%s).', len, dirtyComponents.length); dirtyComponents.sort(mountOrderComparator); for(var i=0;i> * * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * !! This file is a check-in of a static_upstream project! !! * !! !! * !! You should not modify this file directly. Instead: !! * !! 1) Use `fjs use-upstream` to temporarily replace this with !! * !! the latest version from upstream. !! * !! 2) Make your changes, test them, etc. !! * !! 3) Use `fjs push-upstream` to copy your changes back to !! * !! static_upstream. !! * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * * Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic * Denicola * * 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. * * @preserve-header * @providesModule ImmediateImplementation */ (function(global,undefined){ "use strict"; var nextHandle=1; var tasksByHandle={}; var queueHead={}; var queueTail=queueHead; var currentlyRunningATask=false; var doc=global.document; var setImmediate; function addFromSetImmediateArguments(args){ var handler=args[0]; args=Array.prototype.slice.call(args,1); tasksByHandle[nextHandle]=function(){ handler.apply(undefined,args);}; queueTail=queueTail.next={handle:nextHandle++}; return queueTail.handle;} function flushQueue(){ var next,task; while(!currentlyRunningATask&&(next=queueHead.next)){ queueHead=next; if(task=tasksByHandle[next.handle]){ currentlyRunningATask=true; try{ task(); currentlyRunningATask=false;}finally { clearImmediate(next.handle); if(currentlyRunningATask){ currentlyRunningATask=false; if(queueHead.next){ setImmediate(flushQueue);}}}}}} function clearImmediate(handle){ delete tasksByHandle[handle];} function canUsePostMessage(){ if(global.postMessage&&!global.importScripts){ var postMessageIsAsynchronous=true; var onMessage=function(){ postMessageIsAsynchronous=false; if(global.removeEventListener){ global.removeEventListener("message",onMessage,false);}else { global.detachEvent("onmessage",onMessage);}}; if(global.addEventListener){ global.addEventListener("message",onMessage,false);}else if(global.attachEvent){ global.attachEvent("onmessage",onMessage);}else { return false;} global.postMessage("","*"); return postMessageIsAsynchronous;}} function installPostMessageImplementation(){ var messagePrefix="setImmediate$"+Math.random()+"$"; var onGlobalMessage=function(event){ if(event.source===global&& typeof event.data==="string"&& event.data.indexOf(messagePrefix)===0){ flushQueue();}}; if(global.addEventListener){ global.addEventListener("message",onGlobalMessage,false);}else { global.attachEvent("onmessage",onGlobalMessage);} setImmediate=function(){ var handle=addFromSetImmediateArguments(arguments); global.postMessage(messagePrefix+handle,"*"); return handle;};} function installMessageChannelImplementation(){ var channel=new MessageChannel(); channel.port1.onmessage=flushQueue; setImmediate=function(){ var handle=addFromSetImmediateArguments(arguments); channel.port2.postMessage(handle); return handle;};} function installReadyStateChangeImplementation(){ var html=doc.documentElement; setImmediate=function(){ var handle=addFromSetImmediateArguments(arguments); var script=doc.createElement("script"); script.onreadystatechange=function(){ script.onreadystatechange=null; html.removeChild(script); script=null; flushQueue();}; html.appendChild(script); return handle;};} function installSetTimeoutImplementation(){ setImmediate=function(){ setTimeout(flushQueue,0); return addFromSetImmediateArguments(arguments);};} if(canUsePostMessage()){ installPostMessageImplementation();}else if(global.MessageChannel){ installMessageChannelImplementation();}else if(doc&&"onreadystatechange" in doc.createElement("script")){ installReadyStateChangeImplementation();}else { installSetTimeoutImplementation();} exports.setImmediate=setImmediate; exports.clearImmediate=clearImmediate;})( Function("return this")()); }); __d('promise/setimmediate/es6-extensions.js',function(global, require, module, exports) { 'use strict'; var Promise=require('promise/setimmediate/core.js'); module.exports=Promise; var TRUE=valuePromise(true); var FALSE=valuePromise(false); var NULL=valuePromise(null); var UNDEFINED=valuePromise(undefined); var ZERO=valuePromise(0); var EMPTYSTRING=valuePromise(''); function valuePromise(value){ var p=new Promise(Promise._99); p._37=1; p._12=value; return p;} Promise.resolve=function(value){ if(value instanceof Promise)return value; if(value===null)return NULL; if(value===undefined)return UNDEFINED; if(value===true)return TRUE; if(value===false)return FALSE; if(value===0)return ZERO; if(value==='')return EMPTYSTRING; if(typeof value==='object'||typeof value==='function'){ try{ var then=value.then; if(typeof then==='function'){ return new Promise(then.bind(value));}} catch(ex) { return new Promise(function(resolve,reject){ reject(ex);});}} return valuePromise(value);}; Promise.all=function(arr){ var args=Array.prototype.slice.call(arr); return new Promise(function(resolve,reject){ if(args.length===0)return resolve([]); var remaining=args.length; function res(i,val){ if(val&&(typeof val==='object'||typeof val==='function')){ if(val instanceof Promise&&val.then===Promise.prototype.then){ while(val._37===3){ val=val._12;} if(val._37===1)return res(i,val._12); if(val._37===2)reject(val._12); val.then(function(val){ res(i,val);}, reject); return;}else { var then=val.then; if(typeof then==='function'){ var p=new Promise(then.bind(val)); p.then(function(val){ res(i,val);}, reject); return;}}} args[i]=val; if(--remaining===0){ resolve(args);}} for(var i=0;i0&&aGenerated.column>=0&& !aOriginal&&!aSource&&!aName){ return;}else if(aGenerated&&'line' in aGenerated&&'column' in aGenerated&& aOriginal&&'line' in aOriginal&&'column' in aOriginal&& aGenerated.line>0&&aGenerated.column>=0&& aOriginal.line>0&&aOriginal.column>=0&& aSource){ return;}else { throw new Error('Invalid mapping: '+JSON.stringify({ generated:aGenerated, source:aSource, orginal:aOriginal, name:aName}));}}; SourceMapGenerator.prototype._serializeMappings= function SourceMapGenerator_serializeMappings(){ var previousGeneratedColumn=0; var previousGeneratedLine=1; var previousOriginalColumn=0; var previousOriginalLine=0; var previousName=0; var previousSource=0; var result=''; var mapping; this._mappings.sort(util.compareByGeneratedPositions); for(var i=0,len=this._mappings.length;i0){ if(!util.compareByGeneratedPositions(mapping,this._mappings[i-1])){ continue;} result+=',';}} result+=base64VLQ.encode(mapping.generatedColumn- previousGeneratedColumn); previousGeneratedColumn=mapping.generatedColumn; if(mapping.source){ result+=base64VLQ.encode(this._sources.indexOf(mapping.source)- previousSource); previousSource=this._sources.indexOf(mapping.source); result+=base64VLQ.encode(mapping.originalLine-1- previousOriginalLine); previousOriginalLine=mapping.originalLine-1; result+=base64VLQ.encode(mapping.originalColumn- previousOriginalColumn); previousOriginalColumn=mapping.originalColumn; if(mapping.name){ result+=base64VLQ.encode(this._names.indexOf(mapping.name)- previousName); previousName=this._names.indexOf(mapping.name);}}} return result;}; SourceMapGenerator.prototype._generateSourcesContent= function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){ return aSources.map(function(source){ if(!this._sourcesContents){ return null;} if(aSourceRoot){ source=util.relative(aSourceRoot,source);} var key=util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)? this._sourcesContents[key]: null;}, this);}; SourceMapGenerator.prototype.toJSON= function SourceMapGenerator_toJSON(){ var map={ version:this._version, file:this._file, sources:this._sources.toArray(), names:this._names.toArray(), mappings:this._serializeMappings()}; if(this._sourceRoot){ map.sourceRoot=this._sourceRoot;} if(this._sourcesContents){ map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot);} return map;}; SourceMapGenerator.prototype.toString= function SourceMapGenerator_toString(){ return JSON.stringify(this);}; exports.SourceMapGenerator=SourceMapGenerator;}); define('source-map/base64-vlq',['require','exports','module','source-map/base64'],function(require,exports,module){ var base64=require('./base64'); var VLQ_BASE_SHIFT=5; var VLQ_BASE=1<>1; return isNegative? -shifted: shifted;} exports.encode=function base64VLQ_encode(aValue){ var encoded=""; var digit; var vlq=toVLQSigned(aValue); do { digit=vlq&VLQ_BASE_MASK; vlq>>>=VLQ_BASE_SHIFT; if(vlq>0){ digit|=VLQ_CONTINUATION_BIT;} encoded+=base64.encode(digit);}while( vlq>0); return encoded;}; exports.decode=function base64VLQ_decode(aStr){ var i=0; var strLen=aStr.length; var result=0; var shift=0; var continuation,digit; do { if(i>=strLen){ throw new Error("Expected more digits in base 64 VLQ value.");} digit=base64.decode(aStr.charAt(i++)); continuation=!!(digit&VLQ_CONTINUATION_BIT); digit&=VLQ_BASE_MASK; result=result+(digit<s2)-(s1=0&&aIdx0){ if(str.charAt(0)===';'){ generatedLine++; str=str.slice(1); previousGeneratedColumn=0;}else if(str.charAt(0)===','){ str=str.slice(1);}else { mapping={}; mapping.generatedLine=generatedLine; temp=base64VLQ.decode(str); mapping.generatedColumn=previousGeneratedColumn+temp.value; previousGeneratedColumn=mapping.generatedColumn; str=temp.rest; if(str.length>0&&!mappingSeparator.test(str.charAt(0))){ temp=base64VLQ.decode(str); mapping.source=this._sources.at(previousSource+temp.value); previousSource+=temp.value; str=temp.rest; if(str.length===0||mappingSeparator.test(str.charAt(0))){ throw new Error('Found a source, but no line and column');} temp=base64VLQ.decode(str); mapping.originalLine=previousOriginalLine+temp.value; previousOriginalLine=mapping.originalLine; mapping.originalLine+=1; str=temp.rest; if(str.length===0||mappingSeparator.test(str.charAt(0))){ throw new Error('Found a source and line, but no column');} temp=base64VLQ.decode(str); mapping.originalColumn=previousOriginalColumn+temp.value; previousOriginalColumn=mapping.originalColumn; str=temp.rest; if(str.length>0&&!mappingSeparator.test(str.charAt(0))){ temp=base64VLQ.decode(str); mapping.name=this._names.at(previousName+temp.value); previousName+=temp.value; str=temp.rest;}} this.__generatedMappings.push(mapping); if(typeof mapping.originalLine==='number'){ this.__originalMappings.push(mapping);}}} this.__originalMappings.sort(util.compareByOriginalPositions);}; SourceMapConsumer.prototype._findMapping= function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName, aColumnName,aComparator){ if(aNeedle[aLineName]<=0){ throw new TypeError('Line must be greater than or equal to 1, got '+ aNeedle[aLineName]);} if(aNeedle[aColumnName]<0){ throw new TypeError('Column must be greater than or equal to 0, got '+ aNeedle[aColumnName]);} return binarySearch.search(aNeedle,aMappings,aComparator);}; SourceMapConsumer.prototype.originalPositionFor= function SourceMapConsumer_originalPositionFor(aArgs){ var needle={ generatedLine:util.getArg(aArgs,'line'), generatedColumn:util.getArg(aArgs,'column')}; var mapping=this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions); if(mapping){ var source=util.getArg(mapping,'source',null); if(source&&this.sourceRoot){ source=util.join(this.sourceRoot,source);} return { source:source, line:util.getArg(mapping,'originalLine',null), column:util.getArg(mapping,'originalColumn',null), name:util.getArg(mapping,'name',null)};} return { source:null, line:null, column:null, name:null};}; SourceMapConsumer.prototype.sourceContentFor= function SourceMapConsumer_sourceContentFor(aSource){ if(!this.sourcesContent){ return null;} if(this.sourceRoot){ aSource=util.relative(this.sourceRoot,aSource);} if(this._sources.has(aSource)){ return this.sourcesContent[this._sources.indexOf(aSource)];} var url; if(this.sourceRoot&&( url=util.urlParse(this.sourceRoot))){ var fileUriAbsPath=aSource.replace(/^file:\/\//,""); if(url.scheme=="file"&& this._sources.has(fileUriAbsPath)){ return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];} if((!url.path||url.path=="/")&& this._sources.has("/"+aSource)){ return this.sourcesContent[this._sources.indexOf("/"+aSource)];}} throw new Error('"'+aSource+'" is not in the SourceMap.');}; SourceMapConsumer.prototype.generatedPositionFor= function SourceMapConsumer_generatedPositionFor(aArgs){ var needle={ source:util.getArg(aArgs,'source'), originalLine:util.getArg(aArgs,'line'), originalColumn:util.getArg(aArgs,'column')}; if(this.sourceRoot){ needle.source=util.relative(this.sourceRoot,needle.source);} var mapping=this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions); if(mapping){ return { line:util.getArg(mapping,'generatedLine',null), column:util.getArg(mapping,'generatedColumn',null)};} return { line:null, column:null};}; SourceMapConsumer.GENERATED_ORDER=1; SourceMapConsumer.ORIGINAL_ORDER=2; SourceMapConsumer.prototype.eachMapping= function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){ var context=aContext||null; var order=aOrder||SourceMapConsumer.GENERATED_ORDER; var mappings; switch(order){ case SourceMapConsumer.GENERATED_ORDER: mappings=this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings=this._originalMappings; break; default: throw new Error("Unknown order of iteration.");} var sourceRoot=this.sourceRoot; mappings.map(function(mapping){ var source=mapping.source; if(source&&sourceRoot){ source=util.join(sourceRoot,source);} return { source:source, generatedLine:mapping.generatedLine, generatedColumn:mapping.generatedColumn, originalLine:mapping.originalLine, originalColumn:mapping.originalColumn, name:mapping.name};}). forEach(aCallback,context);}; exports.SourceMapConsumer=SourceMapConsumer;}); define('source-map/binary-search',['require','exports','module'],function(require,exports,module){ function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){ var mid=Math.floor((aHigh-aLow)/2)+aLow; var cmp=aCompare(aNeedle,aHaystack[mid],true); if(cmp===0){ return aHaystack[mid];}else if(cmp>0){ if(aHigh-mid>1){ return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare);} return aHaystack[mid];}else { if(mid-aLow>1){ return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare);} return aLow<0? null: aHaystack[aLow];}} exports.search=function search(aNeedle,aHaystack,aCompare){ return aHaystack.length>0? recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare): null;};}); define('source-map/source-node',['require','exports','module','source-map/source-map-generator','source-map/util'],function(require,exports,module){ var SourceMapGenerator=require('./source-map-generator').SourceMapGenerator; var util=require('./util'); function SourceNode(aLine,aColumn,aSource,aChunks,aName){ this.children=[]; this.sourceContents={}; this.line=aLine===undefined?null:aLine; this.column=aColumn===undefined?null:aColumn; this.source=aSource===undefined?null:aSource; this.name=aName===undefined?null:aName; if(aChunks!=null)this.add(aChunks);} SourceNode.fromStringWithSourceMap= function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer){ var node=new SourceNode(); var remainingLines=aGeneratedCode.split('\n'); var lastGeneratedLine=1,lastGeneratedColumn=0; var lastMapping=null; aSourceMapConsumer.eachMapping(function(mapping){ if(lastMapping===null){ while(lastGeneratedLine=0;i--){ this.prepend(aChunk[i]);}}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){ this.children.unshift(aChunk);}else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk);} return this;}; SourceNode.prototype.walk=function SourceNode_walk(aFn){ var chunk; for(var i=0,len=this.children.length;i0){ newChildren=[]; for(i=0;i-1?upcased:method;} function Request(input,options){ options=options||{}; var body=options.body; if(Request.prototype.isPrototypeOf(input)){ if(input.bodyUsed){ throw new TypeError('Already read');} this.url=input.url; this.credentials=input.credentials; if(!options.headers){ this.headers=new Headers(input.headers);} this.method=input.method; this.mode=input.mode; if(!body){ body=input._bodyInit; input.bodyUsed=true;}}else { this.url=input;} this.credentials=options.credentials||this.credentials||'omit'; if(options.headers||!this.headers){ this.headers=new Headers(options.headers);} this.method=normalizeMethod(options.method||this.method||'GET'); this.mode=options.mode||this.mode||null; this.referrer=null; if((this.method==='GET'||this.method==='HEAD')&&body){ throw new TypeError('Body not allowed for GET or HEAD requests');} this._initBody(body);} Request.prototype.clone=function(){ return new Request(this);}; function decode(body){ var form=new FormData(); body.trim().split('&').forEach(function(bytes){ if(bytes){ var split=bytes.split('='); var name=split.shift().replace(/\+/g,' '); var value=split.join('=').replace(/\+/g,' '); form.append(decodeURIComponent(name),decodeURIComponent(value));}}); return form;} function headers(xhr){ var head=new Headers(); var pairs=xhr.getAllResponseHeaders().trim().split('\n'); pairs.forEach(function(header){ var split=header.trim().split(':'); var key=split.shift().trim(); var value=split.join(':').trim(); head.append(key,value);}); return head;} Body.call(Request.prototype); function Response(bodyInit,options){ if(!options){ options={};} this._initBody(bodyInit); this.type='default'; this.url=null; this.status=options.status; this.ok=this.status>=200&&this.status<300; this.statusText=options.statusText; this.headers=options.headers instanceof Headers?options.headers:new Headers(options.headers); this.url=options.url||'';} Response.prototype.clone=function(){ return new Response(this._bodyInit,{ status:this.status, statusText:this.statusText, headers:new Headers(this.headers), url:this.url});}; Body.call(Response.prototype); self.Headers=Headers; self.Request=Request; self.Response=Response; self.fetch=function(input,init){ var request; if(Request.prototype.isPrototypeOf(input)&&!init){ request=input;}else { request=new Request(input,init);} return new Promise(function(resolve,reject){ var xhr=new XMLHttpRequest(); function responseURL(){ if('responseURL' in xhr){ return xhr.responseURL;} if(/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())){ return xhr.getResponseHeader('X-Request-URL');} return;} xhr.onload=function(){ var status=xhr.status===1223?204:xhr.status; if(status<100||status>599){ reject(new TypeError('Network request failed')); return;} var options={ status:status, statusText:xhr.statusText, headers:headers(xhr), url:responseURL()}; var body='response' in xhr?xhr.response:xhr.responseText; resolve(new Response(body,options));}; xhr.onerror=function(){ reject(new TypeError('Network request failed'));}; xhr.open(request.method,request.url,true); if(request.credentials==='include'){ xhr.withCredentials=true;} if('responseType' in xhr&&support.blob){ xhr.responseType='blob';} request.headers.forEach(function(value,name){ xhr.setRequestHeader(name,value);}); xhr.send(typeof request._bodyInit==='undefined'?null:request._bodyInit);});}; self.fetch.polyfill=true;})(); module.exports=self; }); __d('Geolocation',function(global, require, module, exports) { 'use strict'; var RCTDeviceEventEmitter=require('RCTDeviceEventEmitter'); var RCTLocationObserver=require('NativeModules').LocationObserver; var invariant=require('invariant'); var logError=require('logError'); var warning=require('warning'); var subscriptions=[]; var updatesEnabled=false; var Geolocation={ getCurrentPosition:function( geo_success, geo_error, geo_options) { invariant( typeof geo_success==='function', 'Must provide a valid geo_success callback.'); RCTLocationObserver.getCurrentPosition( geo_options||{}, geo_success, geo_error||logError);}, watchPosition:function(success,error,options){ if(!updatesEnabled){ RCTLocationObserver.startObserving(options||{}); updatesEnabled=true;} var watchID=subscriptions.length; subscriptions.push([ RCTDeviceEventEmitter.addListener( 'geolocationDidChange', success), error?RCTDeviceEventEmitter.addListener( 'geolocationError', error): null]); return watchID;}, clearWatch:function(watchID){ var sub=subscriptions[watchID]; if(!sub){ return;} sub[0].remove(); var sub1=sub[1];sub1&&sub1.remove(); subscriptions[watchID]=undefined; var noWatchers=true; for(var ii=0;ii0){ var types=Array(arguments.length); for(var i=0;i1){ var index=id.indexOf(SEPARATOR,1); return index>-1?id.substr(0,index):id;} return null;}, 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);}}, traverseTwoPhase:function(targetID,cb,arg){ if(targetID){ traverseParentPath('',targetID,cb,arg,true,false); traverseParentPath(targetID,'',cb,arg,false,true);}}, traverseTwoPhaseSkipTarget:function(targetID,cb,arg){ if(targetID){ traverseParentPath('',targetID,cb,arg,true,true); traverseParentPath(targetID,'',cb,arg,true,true);}}, traverseAncestors:function(targetID,cb,arg){ traverseParentPath('',targetID,cb,arg,true,false);}, getFirstCommonAncestorID:getFirstCommonAncestorID, _getNextDescendantID:getNextDescendantID, isAncestorIDOf:isAncestorIDOf, SEPARATOR:SEPARATOR}; module.exports=ReactInstanceHandles; }); __d('ReactRootIndex',function(global, require, module, exports) { 'use strict'; var ReactRootIndexInjection={ injectCreateReactRootIndex:function(_createReactRootIndex){ ReactRootIndex.createReactRootIndex=_createReactRootIndex;}}; var ReactRootIndex={ createReactRootIndex:null, injection:ReactRootIndexInjection}; module.exports=ReactRootIndex; }); __d('ReactNativeMount',function(global, require, module, exports) { 'use strict'; var RCTUIManager=require('NativeModules').UIManager; var ReactElement=require('ReactElement'); var ReactNativeTagHandles=require('ReactNativeTagHandles'); var ReactNativeViewPool=require('ReactNativeViewPool'); var ReactPerf=require('ReactPerf'); var ReactReconciler=require('ReactReconciler'); var ReactUpdateQueue=require('ReactUpdateQueue'); var ReactUpdates=require('ReactUpdates'); var emptyObject=require('emptyObject'); var instantiateReactComponent=require('instantiateReactComponent'); var shouldUpdateReactComponent=require('shouldUpdateReactComponent'); function instanceNumberToChildRootID(rootNodeID,instanceNumber){ return rootNodeID+'['+instanceNumber+']';} var TopLevelWrapper=function(){}; TopLevelWrapper.prototype.isReactComponent={}; if(__DEV__){ TopLevelWrapper.displayName='TopLevelWrapper';} TopLevelWrapper.prototype.render=function(){ return this.props;}; function mountComponentIntoNode( componentInstance, rootID, container, transaction){ var markup=ReactReconciler.mountComponent( componentInstance,rootID,transaction,emptyObject); componentInstance._renderedComponent._topLevelWrapper=componentInstance; ReactNativeMount._mountImageIntoNode(markup,container);} function batchedMountComponentIntoNode( componentInstance, rootID, container){ var transaction=ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform( mountComponentIntoNode, null, componentInstance, rootID, container, transaction); ReactUpdates.ReactReconcileTransaction.release(transaction);} var ReactNativeMount={ instanceCount:0, _instancesByContainerID:{}, findNodeHandle:require('findNodeHandle'), nativeTagToRootNodeID:function(nativeTag){ return ReactNativeTagHandles.tagToRootNodeID[nativeTag];}, renderComponent:function( nextElement, containerTag, callback) { var nextWrappedElement=new ReactElement( TopLevelWrapper, null, null, null, null, null, nextElement); var topRootNodeID=ReactNativeTagHandles.tagToRootNodeID[containerTag]; if(topRootNodeID){ var prevComponent=ReactNativeMount._instancesByContainerID[topRootNodeID]; if(prevComponent){ var prevWrappedElement=prevComponent._currentElement; var prevElement=prevWrappedElement.props; if(shouldUpdateReactComponent(prevElement,nextElement)){ ReactUpdateQueue.enqueueElementInternal(prevComponent,nextWrappedElement); if(callback){ ReactUpdateQueue.enqueueCallbackInternal(prevComponent,callback);} return prevComponent;}else { ReactNativeMount.unmountComponentAtNode(containerTag);}}} if(!ReactNativeTagHandles.reactTagIsNativeTopRootID(containerTag)){ console.error('You cannot render into anything but a top root'); return;} var topRootNodeID=ReactNativeTagHandles.allocateRootNodeIDForTag(containerTag); ReactNativeTagHandles.associateRootNodeIDWithMountedNodeHandle( topRootNodeID, containerTag); var instance=instantiateReactComponent(nextWrappedElement); ReactNativeMount._instancesByContainerID[topRootNodeID]=instance; var childRootNodeID=instanceNumberToChildRootID( topRootNodeID, ReactNativeMount.instanceCount++); ReactUpdates.batchedUpdates( batchedMountComponentIntoNode, instance, childRootNodeID, topRootNodeID); var component=instance.getPublicInstance(); if(callback){ callback.call(component);} return component;}, _mountImageIntoNode:ReactPerf.measure( 'ReactComponentBrowserEnvironment', 'mountImageIntoNode', function(mountImage,containerID){ ReactNativeTagHandles.associateRootNodeIDWithMountedNodeHandle( mountImage.rootNodeID, mountImage.tag); var addChildTags=[mountImage.tag]; var addAtIndices=[0]; RCTUIManager.manageChildren( ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(containerID), null, null, addChildTags, addAtIndices, null);}), unmountComponentAtNodeAndRemoveContainer:function( containerTag) { ReactNativeMount.unmountComponentAtNode(containerTag); RCTUIManager.removeRootView(containerTag); ReactNativeViewPool.clearPoolForRootView(containerTag);}, unmountComponentAtNode:function(containerTag){ if(!ReactNativeTagHandles.reactTagIsNativeTopRootID(containerTag)){ console.error('You cannot render into anything but a top root'); return false;} var containerID=ReactNativeTagHandles.tagToRootNodeID[containerTag]; var instance=ReactNativeMount._instancesByContainerID[containerID]; if(!instance){ return false;} ReactNativeMount.unmountComponentFromNode(instance,containerID); delete ReactNativeMount._instancesByContainerID[containerID]; return true;}, unmountComponentFromNode:function( instance, containerID) { ReactReconciler.unmountComponent(instance); var containerTag= ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(containerID); RCTUIManager.removeSubviewsFromContainerWithID(containerTag);}, getNode:function(rootNodeID){ return ReactNativeTagHandles.rootNodeIDToTag[rootNodeID];}, getID:function(nativeTag){ return ReactNativeTagHandles.tagToRootNodeID[nativeTag];}}; ReactNativeMount.renderComponent=ReactPerf.measure( 'ReactMount', '_renderNewRootComponent', ReactNativeMount.renderComponent); module.exports=ReactNativeMount; }); __d('ReactElement',function(global, require, module, exports) { 'use strict'; var ReactCurrentOwner=require('ReactCurrentOwner'); var assign=require('Object.assign'); var canDefineProperty=require('canDefineProperty'); var REACT_ELEMENT_TYPE= typeof Symbol==='function'&&Symbol.for&&Symbol.for('react.element')|| 0xeac7; var RESERVED_PROPS={ key:true, ref:true, __self:true, __source:true}; var ReactElement=function(type,key,ref,self,source,owner,props){ var element={ $$typeof:REACT_ELEMENT_TYPE, type:type, key:key, ref:ref, props:props, _owner:owner}; if(__DEV__){ element._store={}; if(canDefineProperty){ Object.defineProperty(element._store,'validated',{ configurable:false, enumerable:false, writable:true, value:false}); Object.defineProperty(element,'_self',{ configurable:false, enumerable:false, writable:false, value:self}); 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; 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; for(propName in config){ if(config.hasOwnProperty(propName)&& !RESERVED_PROPS.hasOwnProperty(propName)){ props[propName]=config[propName];}}} var childrenLength=arguments.length-2; if(childrenLength===1){ props.children=children;}else if(childrenLength>1){ var childArray=Array(childrenLength); for(var i=0;i1){ var childArray=Array(childrenLength); for(var i=0;i0){ RCTUIManager.dropViews(this._viewsToDelete);} var addToPoolTags=this._addToPool[TAGS_IDX]; var addToPoolKeys=this._addToPool[KEYS_IDX]; var addToPoolProps=this._addToPool[PROPS_IDX]; for(var i=addToPoolTags.length-1;i>=0;i--){ var nativeTag=addToPoolTags[i]; var key=addToPoolKeys[i]; var props=addToPoolProps[i]; var views=this._pool[key]||[[],[]]; views[0].push(nativeTag); views[1].push(props); this._pool[key]=views;} this._viewsToDelete=[]; this._addToPool=[[],[],[]]; this._poolQueue={};}},{key:'acquire',value:function acquire( viewRef,rootTag){ var key=poolKey(viewRef); if((this._pool[key]||EMPTY_POOL)[0].length){ var views=this._pool[key]; var nativeTag=views[0].pop(); var oldProps=views[1].pop(); var updatePayload=ReactNativeAttributePayload.diff( oldProps, getViewProps(viewRef), getViewValidAttributes(viewRef)); if(__DEV__){ this._recycleStats[key]=(this._recycleStats[key]||0)+1;} if(updatePayload){ RCTUIManager.updateView( nativeTag, viewRef.viewConfig.uiViewClassName, updatePayload);} return nativeTag;}else { return enqueueCreate(viewRef,rootTag);}}},{key:'release',value:function release( viewRef){ var key=poolKey(viewRef); var nativeTag=getViewTag(viewRef); var pooledCount=(this._pool[key]||EMPTY_POOL)[0].length+(this._poolQueue[key]||0); if(pooledCount<(_poolSize[key]||0)){ this._addToPool[TAGS_IDX].push(nativeTag); this._addToPool[KEYS_IDX].push(key); this._addToPool[PROPS_IDX].push(getViewProps(viewRef)); this._poolQueue[key]=(this._poolQueue[key]||0)+1;}else { if(__DEV__){ if(_poolSize[key]){ this._deleteStats[key]=(this._deleteStats[key]||0)+1;}} this._viewsToDelete.push(nativeTag);}}},{key:'clear',value:function clear() { for(var key in this._pool){ var poolTags=this._pool[key][0]; for(var i=poolTags.length-1;i>=0;i--){ this._viewsToDelete.push(poolTags[i]);}} var addToPoolTags=this._addToPool[0]; for(var i=addToPoolTags.length-1;i>=0;i--){ this._viewsToDelete.push(addToPoolTags[i]);} this._addToPool=[[],[],[]]; this.onReconcileTransactionClose();}},{key:'printStats',value:function printStats() { if(__DEV__){ console.log('Stats',this._recycleStats,this._deleteStats);}}}]);return ReactNativeViewPool;})(); module.exports={ onReconcileTransactionClose:function(){ if(ENABLED){ for(var pool in _pools){ _pools[pool].onReconcileTransactionClose();}}}, acquire:function(viewRef){ var rootTag=getRootViewTag(viewRef); if(ENABLED){ var pool=_pools[rootTag]; if(!pool){ pool=_pools[rootTag]=new ReactNativeViewPool();} return pool.acquire(viewRef,rootTag);}else { return enqueueCreate(viewRef,rootTag);}}, release:ENABLED?function(viewRef){ var pool=_pools[getRootViewTag(viewRef)]; if(pool){ pool.release(viewRef);}}: emptyFunction, clearPoolForRootView:ENABLED?function(rootID){ var pool=_pools[rootID]; if(pool){ pool.clear(); delete _pools[rootID];}}: emptyFunction, configure:function(pool_size){ _poolSize=pool_size;}, printStats:function(){ if(__DEV__){ console.log('Pool size',_poolSize); for(var pool in _pools){ _pools[pool].onReconcileTransactionClose();}}}}; }); __d('ReactNativeAttributePayload',function(global, require, module, exports) { 'use strict'; var Platform=require('Platform'); var deepDiffer=require('deepDiffer'); var styleDiffer=require('styleDiffer'); var flattenStyle=require('flattenStyle'); function translateKey(propKey){ if(propKey==='transform'){ if(Platform.OS==='android'){ return 'decomposedMatrix';}else { return 'transformMatrix';}} return propKey;} function defaultDiffer(prevProp,nextProp){ if(typeof nextProp!=='object'||nextProp===null){ return true;}else { return deepDiffer(prevProp,nextProp);}} function diffNestedProperty( updatePayload, prevProp, nextProp, validAttributes) { if(!styleDiffer(prevProp,nextProp)){ return updatePayload;} var previousFlattenedStyle=flattenStyle(prevProp); var nextFlattenedStyle=flattenStyle(nextProp); if(!previousFlattenedStyle||!nextFlattenedStyle){ if(nextFlattenedStyle){ return addProperties( updatePayload, nextFlattenedStyle, validAttributes);} if(previousFlattenedStyle){ return clearProperties( updatePayload, previousFlattenedStyle, validAttributes);} return updatePayload;} return diffProperties( updatePayload, previousFlattenedStyle, nextFlattenedStyle, validAttributes);} function clearNestedProperty( updatePayload, prevProp, validAttributes) { return diffNestedProperty(updatePayload,prevProp,{},validAttributes);} function diffProperties( updatePayload, prevProps, nextProps, validAttributes) { var attributeConfig; var nextProp; var prevProp; for(var propKey in nextProps){ attributeConfig=validAttributes[propKey]; if(!attributeConfig){ continue;} var altKey=translateKey(propKey); if(!validAttributes[altKey]){ altKey=propKey;} if(updatePayload&&updatePayload[altKey]!==undefined){ continue;} prevProp=prevProps[propKey]; nextProp=nextProps[propKey]; if(typeof nextProp==='function'){ nextProp=true; if(typeof prevProp==='function'){ prevProp=true;}} if(prevProp===nextProp){ continue;} if(typeof attributeConfig!=='object'){ if(defaultDiffer(prevProp,nextProp)){ (updatePayload||(updatePayload={}))[altKey]=nextProp;}}else if(typeof attributeConfig.diff==='function'|| typeof attributeConfig.process==='function'){ var shouldUpdate=prevProp===undefined||( typeof attributeConfig.diff==='function'? attributeConfig.diff(prevProp,nextProp): defaultDiffer(prevProp,nextProp)); if(shouldUpdate){ var nextValue=typeof attributeConfig.process==='function'? attributeConfig.process(nextProp): nextProp; (updatePayload||(updatePayload={}))[altKey]=nextValue;}}else { updatePayload=diffNestedProperty( updatePayload, prevProp, nextProp, attributeConfig);}} for(var propKey in prevProps){ if(nextProps[propKey]!==undefined){ continue;} attributeConfig=validAttributes[propKey]; if(!attributeConfig){ continue;} prevProp=prevProps[propKey]; if(prevProp===undefined){ continue;} if(typeof attributeConfig!=='object'|| typeof attributeConfig.diff==='function'|| typeof attributeConfig.process==='function'){ (updatePayload||(updatePayload={}))[translateKey(propKey)]=null;}else { updatePayload=clearNestedProperty( updatePayload, prevProp, attributeConfig);}} return updatePayload;} function addProperties( updatePayload, props, validAttributes) { return diffProperties(updatePayload,{},props,validAttributes);} function clearProperties( updatePayload, prevProps, validAttributes) { return diffProperties(updatePayload,prevProps,{},validAttributes);} var ReactNativeAttributePayload={ create:function( props, validAttributes) { return addProperties( null, props, validAttributes);}, diff:function( prevProps, nextProps, validAttributes) { return diffProperties( null, prevProps, nextProps, validAttributes);}}; module.exports=ReactNativeAttributePayload; }); __d('deepDiffer',function(global, require, module, exports) { 'use strict'; var deepDiffer=function(one,two){ if(one===two){ return false;} if(typeof one==='function'&&typeof two==='function'){ return false;} if(typeof one!=='object'||one===null){ return one!==two;} if(typeof two!=='object'||two===null){ return true;} if(one.constructor!==two.constructor){ return true;} if(Array.isArray(one)){ var len=one.length; if(two.length!==len){ return true;} for(var ii=0;ii component.'); this._rootNodeID=rootID; var tag=ReactNativeTagHandles.allocateTag(); var nativeTopRootID=ReactNativeTagHandles.getNativeTopRootIDFromNodeID(rootID); RCTUIManager.createView( tag, 'RCTRawText', nativeTopRootID?ReactNativeTagHandles.rootNodeIDToTag[nativeTopRootID]:null, {text:this._stringText}); return { rootNodeID:rootID, tag:tag};}, receiveComponent:function(nextText,transaction,context){ if(nextText!==this._currentElement){ this._currentElement=nextText; var nextStringText=''+nextText; if(nextStringText!==this._stringText){ this._stringText=nextStringText; RCTUIManager.updateView( ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID( this._rootNodeID), 'RCTRawText', {text:this._stringText});}}}, unmountComponent:function(){ this._currentElement=null; this._stringText=null; this._rootNodeID=null;}}); module.exports=ReactNativeTextComponent; }); __d('RCTDebugComponentOwnership',function(global, require, module, exports) { 'use strict'; var DebugComponentOwnershipModule=require('NativeModules').DebugComponentOwnershipModule; var InspectorUtils=require('InspectorUtils'); var ReactNativeTagHandles=require('ReactNativeTagHandles'); function componentToString(component){ return component.getName?component.getName():'Unknown';} function getRootTagForTag(tag){ var rootNodeID=ReactNativeTagHandles.tagToRootNodeID[tag]; if(!rootNodeID){ return null;} var rootID=ReactNativeTagHandles.getNativeTopRootIDFromNodeID(rootNodeID); if(!rootID){ return null;} return ReactNativeTagHandles.rootNodeIDToTag[rootID];} module.exports={ getOwnerHierarchy:function(requestID,tag){ var rootTag=getRootTagForTag(tag); var instance=InspectorUtils.findInstanceByNativeTag(rootTag,tag); var ownerHierarchy=instance? InspectorUtils.getOwnerHierarchy(instance).map(componentToString): null; DebugComponentOwnershipModule.receiveOwnershipHierarchy(requestID,tag,ownerHierarchy);}}; }); __d('InspectorUtils',function(global, require, module, exports) { 'use strict'; var ReactInstanceHandles=require('ReactInstanceHandles'); var ReactInstanceMap=require('ReactInstanceMap'); var ReactNativeMount=require('ReactNativeMount'); var ReactNativeTagHandles=require('ReactNativeTagHandles'); function traverseOwnerTreeUp(hierarchy,instance){ if(instance){ hierarchy.unshift(instance); traverseOwnerTreeUp(hierarchy,instance._currentElement._owner);}} function findInstance(component,targetID){ if(targetID===findRootNodeID(component)){ return component;} if(component._renderedComponent){ return findInstance(component._renderedComponent,targetID);}else { for(var key in component._renderedChildren){ var child=component._renderedChildren[key]; if(ReactInstanceHandles.isAncestorIDOf(findRootNodeID(child),targetID)){ var instance=findInstance(child,targetID); if(instance){ return instance;}}}}} function findRootNodeID(component){ var internalInstance=ReactInstanceMap.get(component); return internalInstance?internalInstance._rootNodeID:component._rootNodeID;} function findInstanceByNativeTag(rootTag,nativeTag){ var containerID=ReactNativeTagHandles.tagToRootNodeID[rootTag]; var rootInstance=ReactNativeMount._instancesByContainerID[containerID]; var targetID=ReactNativeTagHandles.tagToRootNodeID[nativeTag]; if(!targetID){ return undefined;} return findInstance(rootInstance,targetID);} function getOwnerHierarchy(instance){ var hierarchy=[]; traverseOwnerTreeUp(hierarchy,instance); return hierarchy;} module.exports={findInstanceByNativeTag:findInstanceByNativeTag,getOwnerHierarchy:getOwnerHierarchy}; }); __d('PerformanceLogger',function(global, require, module, exports) { 'use strict'; var performanceNow=require('performanceNow'); var timespans={}; var extras={}; var PerformanceLogger={ addTimespan:function(key,lengthInMs,description){ if(timespans[key]){ if(__DEV__){ console.log( 'PerformanceLogger: Attempting to add a timespan that already exists ', key);} return;} timespans[key]={ description:description, totalTime:lengthInMs};}, startTimespan:function(key,description){ if(timespans[key]){ if(__DEV__){ console.log( 'PerformanceLogger: Attempting to start a timespan that already exists ', key);} return;} timespans[key]={ description:description, startTime:performanceNow()};}, stopTimespan:function(key){ if(!timespans[key]||!timespans[key].startTime){ if(__DEV__){ console.log( 'PerformanceLogger: Attempting to end a timespan that has not started ', key);} return;} timespans[key].endTime=performanceNow(); timespans[key].totalTime= timespans[key].endTime-timespans[key].startTime;}, clear:function(){ timespans={}; extras={};}, clearExceptTimespans:function(keys){ timespans=Object.keys(timespans).reduce(function(previous,key){ if(keys.indexOf(key)!==-1){ previous[key]=timespans[key];} return previous;}, {}); extras={};}, getTimespans:function(){ return timespans;}, hasTimespan:function(key){ return !!timespans[key];}, logTimespans:function(){ for(var key in timespans){ if(timespans[key].totalTime){ console.log(key+': '+timespans[key].totalTime+'ms');}}}, addTimespans:function(newTimespans,labels){ for(var i=0,l=newTimespans.length;i-1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in '+ 'the plugin ordering, `%s`.', pluginName); if(EventPluginRegistry.plugins[pluginIndex]){ continue;} invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` '+ 'method, but `%s` does not.', pluginName); EventPluginRegistry.plugins[pluginIndex]=PluginModule; var publishedEvents=PluginModule.eventTypes; for(var eventName in publishedEvents){ invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName);}}} function publishEventForPlugin(dispatchConfig,PluginModule,eventName){ invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same '+ 'event name, `%s`.', eventName); EventPluginRegistry.eventNameDispatchConfigs[eventName]=dispatchConfig; var phasedRegistrationNames=dispatchConfig.phasedRegistrationNames; if(phasedRegistrationNames){ for(var phaseName in phasedRegistrationNames){ if(phasedRegistrationNames.hasOwnProperty(phaseName)){ var phasedRegistrationName=phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, PluginModule, eventName);}} return true;}else if(dispatchConfig.registrationName){ publishRegistrationName( dispatchConfig.registrationName, PluginModule, eventName); return true;} return false;} function publishRegistrationName(registrationName,PluginModule,eventName){ invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same '+ 'registration name, `%s`.', registrationName); EventPluginRegistry.registrationNameModules[registrationName]=PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName]= PluginModule.eventTypes[eventName].dependencies;} var EventPluginRegistry={ plugins:[], eventNameDispatchConfigs:{}, registrationNameModules:{}, registrationNameDependencies:{}, injectEventPluginOrder:function(InjectedEventPluginOrder){ invariant( !EventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than '+ 'once. You are likely trying to load more than one copy of React.'); EventPluginOrder=Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering();}, 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){ invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins '+ 'using the same name, `%s`.', pluginName); namesToPlugins[pluginName]=PluginModule; isOrderingDirty=true;}} if(isOrderingDirty){ recomputePluginOrdering();}}, 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;}, _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; }); __d('EventPluginUtils',function(global, require, module, exports) { 'use strict'; var EventConstants=require('EventConstants'); var ReactErrorUtils=require('ReactErrorUtils'); var invariant=require('invariant'); var warning=require('warning'); var injection={ Mount:null, injectMount:function(InjectedMount){ injection.Mount=InjectedMount; if(__DEV__){ warning( InjectedMount&&InjectedMount.getNode&&InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount '+ 'module is missing getNode or getID.');}}}; 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(__DEV__){ 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; warning( idsIsArr===listenersIsArr&&IDsLen===listenersLen, 'EventPluginUtils: Invalid `event`.');};} 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;} function executeDispatchesInOrder(event,simulated){ var dispatchListeners=event._dispatchListeners; var dispatchIDs=event._dispatchIDs; if(__DEV__){ validateEventDispatches(event);} if(Array.isArray(dispatchListeners)){ for(var i=0;i=len){ this._iteratedObject=undefined; return createIterResultObject(undefined,true);} this._nextIndex=index+1; if(kind===KIND_KEY){ return createIterResultObject(index,false);}else if(kind===KIND_VALUE){ return createIterResultObject(array[index],false);}else if(kind===KIND_KEY_VAL){ return createIterResultObject([index,array[index]],false);}}},{key: '@@iterator',value:function iterator(){ return this;}}]);return ArrayIterator;})();var StringIterator=(function(){ function StringIterator(string){babelHelpers.classCallCheck(this,StringIterator); if(typeof string!=='string'){ throw new TypeError('Object is not a string');} this._iteratedString=string; this._nextIndex=0;}babelHelpers.createClass(StringIterator,[{key:'next',value:function next() { if(!this instanceof StringIterator){ throw new TypeError('Object is not a StringIterator');} if(this._iteratedString==null){ return createIterResultObject(undefined,true);} var index=this._nextIndex; var s=this._iteratedString; var len=s.length; if(index>=len){ this._iteratedString=undefined; return createIterResultObject(undefined,true);} var ret; var first=s.charCodeAt(index); if(first<0xD800||first>0xDBFF||index+1===len){ ret=s[index];}else { var second=s.charCodeAt(index+1); if(second<0xDC00||second>0xDFFF){ ret=s[index];}else { ret=s[index]+s[index+1];}} this._nextIndex=index+ret.length; return createIterResultObject(ret,false);}},{key: '@@iterator',value:function iterator(){ return this;}}]);return StringIterator;})(); function createIterResultObject(value,done){ return {value:value,done:done};} return function(object,kind){ if(typeof object==='string'){ return new StringIterator(object);}else if(Array.isArray(object)){ return new ArrayIterator(object,kind||KIND_VALUE);}else { return object[ITERATOR_SYMBOL]();}};})();}else { return function(object){ return object[ITERATOR_SYMBOL]();};}})(); babelHelpers.extends(toIterator,{ KIND_KEY:KIND_KEY, KIND_VALUE:KIND_VALUE, KIND_KEY_VAL:KIND_KEY_VAL, ITERATOR_SYMBOL:ITERATOR_SYMBOL}); module.exports=toIterator; }); __d('_shouldPolyfillES6Collection',function(global, require, module, exports) { function shouldPolyfillES6Collection(collectionName){ var Collection=global[collectionName]; if(Collection==null){ return true;} if(typeof global.Symbol!=='function'){ return true;} var proto=Collection.prototype; return Collection==null|| typeof Collection!=='function'|| typeof proto.clear!=='function'|| new Collection().size!==0|| typeof proto.keys!=='function'|| typeof proto.forEach!=='function';} module.exports=shouldPolyfillES6Collection; }); __d('ReactNativeGlobalResponderHandler',function(global, require, module, exports) { 'use strict'; var RCTUIManager=require('NativeModules').UIManager; var ReactNativeTagHandles=require('ReactNativeTagHandles'); var ReactNativeGlobalResponderHandler={ onChange:function(from,to,blockNativeResponder){ if(to!==null){ RCTUIManager.setJSResponder( ReactNativeTagHandles.mostRecentMountedNodeHandleForRootNodeID(to), blockNativeResponder);}else { RCTUIManager.clearJSResponder();}}}; module.exports=ReactNativeGlobalResponderHandler; }); __d('ResponderEventPlugin',function(global, require, module, exports) { 'use strict'; var EventConstants=require('EventConstants'); var EventPluginUtils=require('EventPluginUtils'); var EventPropagators=require('EventPropagators'); var ReactInstanceHandles=require('ReactInstanceHandles'); var ResponderSyntheticEvent=require('ResponderSyntheticEvent'); var ResponderTouchHistoryStore=require('ResponderTouchHistoryStore'); var accumulate=require('accumulate'); var invariant=require('invariant'); var keyOf=require('keyOf'); var isStartish=EventPluginUtils.isStartish; var isMoveish=EventPluginUtils.isMoveish; var isEndish=EventPluginUtils.isEndish; var executeDirectDispatch=EventPluginUtils.executeDirectDispatch; var hasDispatches=EventPluginUtils.hasDispatches; var executeDispatchesInOrderStopAtTrue= EventPluginUtils.executeDispatchesInOrderStopAtTrue; var responderID=null; var trackedTouchCount=0; var previousActiveTouches=0; var changeResponder=function(nextResponderID,blockNativeResponder){ var oldResponderID=responderID; responderID=nextResponderID; if(ResponderEventPlugin.GlobalResponderHandler!==null){ ResponderEventPlugin.GlobalResponderHandler.onChange( oldResponderID, nextResponderID, blockNativeResponder);}}; var eventTypes={ startShouldSetResponder:{ phasedRegistrationNames:{ bubbled:keyOf({onStartShouldSetResponder:null}), captured:keyOf({onStartShouldSetResponderCapture:null})}}, scrollShouldSetResponder:{ phasedRegistrationNames:{ bubbled:keyOf({onScrollShouldSetResponder:null}), captured:keyOf({onScrollShouldSetResponderCapture:null})}}, selectionChangeShouldSetResponder:{ phasedRegistrationNames:{ bubbled:keyOf({onSelectionChangeShouldSetResponder:null}), captured:keyOf({onSelectionChangeShouldSetResponderCapture:null})}}, moveShouldSetResponder:{ phasedRegistrationNames:{ bubbled:keyOf({onMoveShouldSetResponder:null}), captured:keyOf({onMoveShouldSetResponderCapture:null})}}, responderStart:{registrationName:keyOf({onResponderStart:null})}, responderMove:{registrationName:keyOf({onResponderMove:null})}, responderEnd:{registrationName:keyOf({onResponderEnd:null})}, responderRelease:{registrationName:keyOf({onResponderRelease:null})}, responderTerminationRequest:{ registrationName:keyOf({onResponderTerminationRequest:null})}, responderGrant:{registrationName:keyOf({onResponderGrant:null})}, responderReject:{registrationName:keyOf({onResponderReject:null})}, responderTerminate:{registrationName:keyOf({onResponderTerminate:null})}}; function setResponderAndExtractTransfer( topLevelType, topLevelTargetID, nativeEvent, nativeEventTarget){ var shouldSetEventType= isStartish(topLevelType)?eventTypes.startShouldSetResponder: isMoveish(topLevelType)?eventTypes.moveShouldSetResponder: topLevelType===EventConstants.topLevelTypes.topSelectionChange? eventTypes.selectionChangeShouldSetResponder: eventTypes.scrollShouldSetResponder; var bubbleShouldSetFrom=!responderID? topLevelTargetID: ReactInstanceHandles.getFirstCommonAncestorID(responderID,topLevelTargetID); var skipOverBubbleShouldSetFrom=bubbleShouldSetFrom===responderID; var shouldSetEvent=ResponderSyntheticEvent.getPooled( shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget); shouldSetEvent.touchHistory=ResponderTouchHistoryStore.touchHistory; if(skipOverBubbleShouldSetFrom){ EventPropagators.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent);}else { EventPropagators.accumulateTwoPhaseDispatches(shouldSetEvent);} var wantsResponderID=executeDispatchesInOrderStopAtTrue(shouldSetEvent); if(!shouldSetEvent.isPersistent()){ shouldSetEvent.constructor.release(shouldSetEvent);} if(!wantsResponderID||wantsResponderID===responderID){ return null;} var extracted; var grantEvent=ResponderSyntheticEvent.getPooled( eventTypes.responderGrant, wantsResponderID, nativeEvent, nativeEventTarget); grantEvent.touchHistory=ResponderTouchHistoryStore.touchHistory; EventPropagators.accumulateDirectDispatches(grantEvent); var blockNativeResponder=executeDirectDispatch(grantEvent)===true; if(responderID){ var terminationRequestEvent=ResponderSyntheticEvent.getPooled( eventTypes.responderTerminationRequest, responderID, nativeEvent, nativeEventTarget); terminationRequestEvent.touchHistory=ResponderTouchHistoryStore.touchHistory; EventPropagators.accumulateDirectDispatches(terminationRequestEvent); var shouldSwitch=!hasDispatches(terminationRequestEvent)|| executeDirectDispatch(terminationRequestEvent); if(!terminationRequestEvent.isPersistent()){ terminationRequestEvent.constructor.release(terminationRequestEvent);} if(shouldSwitch){ var terminateType=eventTypes.responderTerminate; var terminateEvent=ResponderSyntheticEvent.getPooled( terminateType, responderID, nativeEvent, nativeEventTarget); terminateEvent.touchHistory=ResponderTouchHistoryStore.touchHistory; EventPropagators.accumulateDirectDispatches(terminateEvent); extracted=accumulate(extracted,[grantEvent,terminateEvent]); changeResponder(wantsResponderID,blockNativeResponder);}else { var rejectEvent=ResponderSyntheticEvent.getPooled( eventTypes.responderReject, wantsResponderID, nativeEvent, nativeEventTarget); rejectEvent.touchHistory=ResponderTouchHistoryStore.touchHistory; EventPropagators.accumulateDirectDispatches(rejectEvent); extracted=accumulate(extracted,rejectEvent);}}else { extracted=accumulate(extracted,grantEvent); changeResponder(wantsResponderID,blockNativeResponder);} return extracted;} function canTriggerTransfer(topLevelType,topLevelTargetID,nativeEvent){ return topLevelTargetID&&( topLevelType===EventConstants.topLevelTypes.topScroll&& !nativeEvent.responderIgnoreScroll|| trackedTouchCount>0&& topLevelType===EventConstants.topLevelTypes.topSelectionChange|| isStartish(topLevelType)|| isMoveish(topLevelType));} function noResponderTouches(nativeEvent){ var touches=nativeEvent.touches; if(!touches||touches.length===0){ return true;} for(var i=0;i=0, 'Ended a touch event which was not counted in trackedTouchCount.');} ResponderTouchHistoryStore.recordTouchTrack(topLevelType,nativeEvent,nativeEventTarget); var extracted=canTriggerTransfer(topLevelType,topLevelTargetID,nativeEvent)? setResponderAndExtractTransfer( topLevelType, topLevelTargetID, nativeEvent, nativeEventTarget): null; var isResponderTouchStart=responderID&&isStartish(topLevelType); var isResponderTouchMove=responderID&&isMoveish(topLevelType); var isResponderTouchEnd=responderID&&isEndish(topLevelType); var incrementalTouch= isResponderTouchStart?eventTypes.responderStart: isResponderTouchMove?eventTypes.responderMove: isResponderTouchEnd?eventTypes.responderEnd: null; if(incrementalTouch){ var gesture= ResponderSyntheticEvent.getPooled( incrementalTouch, responderID, nativeEvent, nativeEventTarget); gesture.touchHistory=ResponderTouchHistoryStore.touchHistory; EventPropagators.accumulateDirectDispatches(gesture); extracted=accumulate(extracted,gesture);} var isResponderTerminate= responderID&& topLevelType===EventConstants.topLevelTypes.topTouchCancel; var isResponderRelease= responderID&& !isResponderTerminate&& isEndish(topLevelType)&& noResponderTouches(nativeEvent); var finalTouch= isResponderTerminate?eventTypes.responderTerminate: isResponderRelease?eventTypes.responderRelease: null; if(finalTouch){ var finalEvent= ResponderSyntheticEvent.getPooled(finalTouch,responderID,nativeEvent,nativeEventTarget); finalEvent.touchHistory=ResponderTouchHistoryStore.touchHistory; EventPropagators.accumulateDirectDispatches(finalEvent); extracted=accumulate(extracted,finalEvent); changeResponder(null);} var numberActiveTouches= ResponderTouchHistoryStore.touchHistory.numberActiveTouches; if(ResponderEventPlugin.GlobalInteractionHandler&& numberActiveTouches!==previousActiveTouches){ ResponderEventPlugin.GlobalInteractionHandler.onChange( numberActiveTouches);} previousActiveTouches=numberActiveTouches; return extracted;}, GlobalResponderHandler:null, GlobalInteractionHandler:null, injection:{ injectGlobalResponderHandler:function(GlobalResponderHandler){ ResponderEventPlugin.GlobalResponderHandler=GlobalResponderHandler;}, injectGlobalInteractionHandler:function(GlobalInteractionHandler){ ResponderEventPlugin.GlobalInteractionHandler=GlobalInteractionHandler;}}}; module.exports=ResponderEventPlugin; }); __d('ResponderSyntheticEvent',function(global, require, module, exports) { 'use strict'; var SyntheticEvent=require('SyntheticEvent'); var ResponderEventInterface={ touchHistory:function(nativeEvent){ return null;}}; function ResponderSyntheticEvent(dispatchConfig,dispatchMarker,nativeEvent,nativeEventTarget){ SyntheticEvent.call(this,dispatchConfig,dispatchMarker,nativeEvent,nativeEventTarget);} SyntheticEvent.augmentClass(ResponderSyntheticEvent,ResponderEventInterface); module.exports=ResponderSyntheticEvent; }); __d('ResponderTouchHistoryStore',function(global, require, module, exports) { 'use strict'; var EventPluginUtils=require('EventPluginUtils'); var invariant=require('invariant'); var isMoveish=EventPluginUtils.isMoveish; var isStartish=EventPluginUtils.isStartish; var isEndish=EventPluginUtils.isEndish; var MAX_TOUCH_BANK=20; var touchHistory={ touchBank:[], numberActiveTouches:0, indexOfSingleActiveTouch:-1, mostRecentTimeStamp:0}; var timestampForTouch=function(touch){ return touch.timeStamp||touch.timestamp;}; var initializeTouchData=function(touch){ return { touchActive:true, startTimeStamp:timestampForTouch(touch), startPageX:touch.pageX, startPageY:touch.pageY, currentPageX:touch.pageX, currentPageY:touch.pageY, currentTimeStamp:timestampForTouch(touch), previousPageX:touch.pageX, previousPageY:touch.pageY, previousTimeStamp:timestampForTouch(touch)};}; var reinitializeTouchTrack=function(touchTrack,touch){ touchTrack.touchActive=true; touchTrack.startTimeStamp=timestampForTouch(touch); touchTrack.startPageX=touch.pageX; touchTrack.startPageY=touch.pageY; touchTrack.currentPageX=touch.pageX; touchTrack.currentPageY=touch.pageY; touchTrack.currentTimeStamp=timestampForTouch(touch); touchTrack.previousPageX=touch.pageX; touchTrack.previousPageY=touch.pageY; touchTrack.previousTimeStamp=timestampForTouch(touch);}; var validateTouch=function(touch){ var identifier=touch.identifier; invariant(identifier!=null,'Touch object is missing identifier'); if(identifier>MAX_TOUCH_BANK){ console.warn( 'Touch identifier '+identifier+' is greater than maximum '+ 'supported '+MAX_TOUCH_BANK+' which causes performance issues '+ 'backfilling array locations for all of the indices.');}}; var recordStartTouchData=function(touch){ var touchBank=touchHistory.touchBank; var identifier=touch.identifier; var touchTrack=touchBank[identifier]; if(__DEV__){ validateTouch(touch);} if(touchTrack){ reinitializeTouchTrack(touchTrack,touch);}else { touchBank[touch.identifier]=initializeTouchData(touch);} touchHistory.mostRecentTimeStamp=timestampForTouch(touch);}; var recordMoveTouchData=function(touch){ var touchBank=touchHistory.touchBank; var touchTrack=touchBank[touch.identifier]; if(__DEV__){ validateTouch(touch); invariant(touchTrack,'Touch data should have been recorded on start');} touchTrack.touchActive=true; touchTrack.previousPageX=touchTrack.currentPageX; touchTrack.previousPageY=touchTrack.currentPageY; touchTrack.previousTimeStamp=touchTrack.currentTimeStamp; touchTrack.currentPageX=touch.pageX; touchTrack.currentPageY=touch.pageY; touchTrack.currentTimeStamp=timestampForTouch(touch); touchHistory.mostRecentTimeStamp=timestampForTouch(touch);}; var recordEndTouchData=function(touch){ var touchBank=touchHistory.touchBank; var touchTrack=touchBank[touch.identifier]; if(__DEV__){ validateTouch(touch); invariant(touchTrack,'Touch data should have been recorded on start');} touchTrack.previousPageX=touchTrack.currentPageX; touchTrack.previousPageY=touchTrack.currentPageY; touchTrack.previousTimeStamp=touchTrack.currentTimeStamp; touchTrack.currentPageX=touch.pageX; touchTrack.currentPageY=touch.pageY; touchTrack.currentTimeStamp=timestampForTouch(touch); touchTrack.touchActive=false; touchHistory.mostRecentTimeStamp=timestampForTouch(touch);}; var ResponderTouchHistoryStore={ recordTouchTrack:function(topLevelType,nativeEvent){ var touchBank=touchHistory.touchBank; if(isMoveish(topLevelType)){ nativeEvent.changedTouches.forEach(recordMoveTouchData);}else if(isStartish(topLevelType)){ nativeEvent.changedTouches.forEach(recordStartTouchData); touchHistory.numberActiveTouches=nativeEvent.touches.length; if(touchHistory.numberActiveTouches===1){ touchHistory.indexOfSingleActiveTouch=nativeEvent.touches[0].identifier;}}else if(isEndish(topLevelType)){ nativeEvent.changedTouches.forEach(recordEndTouchData); touchHistory.numberActiveTouches=nativeEvent.touches.length; if(touchHistory.numberActiveTouches===1){ for(var i=0;i>';} return propValue.constructor.name;} module.exports=ReactPropTypes; }); __d('getIteratorFn',function(global, require, module, exports) { 'use strict'; var ITERATOR_SYMBOL=typeof Symbol==='function'&&Symbol.iterator; var FAUX_ITERATOR_SYMBOL='@@iterator'; function getIteratorFn(maybeIterable){ var iteratorFn=maybeIterable&&( ITERATOR_SYMBOL&&maybeIterable[ITERATOR_SYMBOL]|| maybeIterable[FAUX_ITERATOR_SYMBOL]); if(typeof iteratorFn==='function'){ return iteratorFn;}} module.exports=getIteratorFn; }); __d('TransformPropTypes',function(global, require, module, exports) { 'use strict'; var ReactPropTypes=require('ReactPropTypes'); var ArrayOfNumberPropType=ReactPropTypes.arrayOf(ReactPropTypes.number); var TransformMatrixPropType=function( props, propName, componentName) { if(props.transform&&props.transformMatrix){ return new Error( 'transformMatrix and transform styles cannot be used on the same '+ 'component');} return ArrayOfNumberPropType(props,propName,componentName);}; var TransformPropTypes={ transform:ReactPropTypes.arrayOf( ReactPropTypes.oneOfType([ ReactPropTypes.shape({perspective:ReactPropTypes.number}), ReactPropTypes.shape({rotate:ReactPropTypes.string}), ReactPropTypes.shape({rotateX:ReactPropTypes.string}), ReactPropTypes.shape({rotateY:ReactPropTypes.string}), ReactPropTypes.shape({rotateZ:ReactPropTypes.string}), ReactPropTypes.shape({scale:ReactPropTypes.number}), ReactPropTypes.shape({scaleX:ReactPropTypes.number}), ReactPropTypes.shape({scaleY:ReactPropTypes.number}), ReactPropTypes.shape({translateX:ReactPropTypes.number}), ReactPropTypes.shape({translateY:ReactPropTypes.number}), ReactPropTypes.shape({skewX:ReactPropTypes.string}), ReactPropTypes.shape({skewY:ReactPropTypes.string})])), transformMatrix:TransformMatrixPropType, scaleX:ReactPropTypes.number, scaleY:ReactPropTypes.number, rotation:ReactPropTypes.number, translateX:ReactPropTypes.number, translateY:ReactPropTypes.number}; module.exports=TransformPropTypes; }); __d('TextStylePropTypes',function(global, require, module, exports) { 'use strict'; var ReactPropTypes=require('ReactPropTypes'); var ViewStylePropTypes=require('ViewStylePropTypes'); var TextStylePropTypes=babelHelpers.extends(Object.create(ViewStylePropTypes),{ color:ReactPropTypes.string, fontFamily:ReactPropTypes.string, fontSize:ReactPropTypes.number, fontStyle:ReactPropTypes.oneOf(['normal','italic']), fontWeight:ReactPropTypes.oneOf( ['normal','bold', '100','200','300','400','500','600','700','800','900']), letterSpacing:ReactPropTypes.number, lineHeight:ReactPropTypes.number, textAlign:ReactPropTypes.oneOf( ['auto','left','right','center','justify']), textDecorationLine:ReactPropTypes.oneOf( ['none','underline','line-through','underline line-through']), textDecorationStyle:ReactPropTypes.oneOf( ['solid','double','dotted','dashed']), textDecorationColor:ReactPropTypes.string, writingDirection:ReactPropTypes.oneOf( ['auto','ltr','rtl'])}); var unsupportedProps=Object.keys({ padding:null, paddingTop:null, paddingLeft:null, paddingRight:null, paddingBottom:null, paddingVertical:null, paddingHorizontal:null}); for(var ii=0;ii1)t-=1; if(t<1/6)return p+(q-p)*6*t; if(t<1/2)return q; if(t<2/3)return p+(q-p)*(2/3-t)*6; return p;} if(s===0){ r=g=b=l;}else { var q=l<0.5?l*(1+s):l+s-l*s; var p=2*l-q; r=hue2rgb(p,q,h+1/3); g=hue2rgb(p,q,h); b=hue2rgb(p,q,h-1/3);} return {r:r*255,g:g*255,b:b*255};} function hsvToRgb(h,s,v){ h=bound01(h,360)*6; s=bound01(s,100); v=bound01(v,100); var i=math.floor(h), f=h-i, p=v*(1-s), q=v*(1-f*s), t=v*(1-(1-f)*s), mod=i%6, r=[v,q,p,p,t,v][mod], g=[t,v,v,q,p,p][mod], b=[p,p,t,v,v,q][mod]; return {r:r*255,g:g*255,b:b*255};} var names=tinycolor.names={ aliceblue:"f0f8ff", antiquewhite:"faebd7", aqua:"0ff", aquamarine:"7fffd4", azure:"f0ffff", beige:"f5f5dc", bisque:"ffe4c4", black:"000", blanchedalmond:"ffebcd", blue:"00f", blueviolet:"8a2be2", brown:"a52a2a", burlywood:"deb887", burntsienna:"ea7e5d", cadetblue:"5f9ea0", chartreuse:"7fff00", chocolate:"d2691e", coral:"ff7f50", cornflowerblue:"6495ed", cornsilk:"fff8dc", crimson:"dc143c", cyan:"0ff", darkblue:"00008b", darkcyan:"008b8b", darkgoldenrod:"b8860b", darkgray:"a9a9a9", darkgreen:"006400", darkgrey:"a9a9a9", darkkhaki:"bdb76b", darkmagenta:"8b008b", darkolivegreen:"556b2f", darkorange:"ff8c00", darkorchid:"9932cc", darkred:"8b0000", darksalmon:"e9967a", darkseagreen:"8fbc8f", darkslateblue:"483d8b", darkslategray:"2f4f4f", darkslategrey:"2f4f4f", darkturquoise:"00ced1", darkviolet:"9400d3", deeppink:"ff1493", deepskyblue:"00bfff", dimgray:"696969", dimgrey:"696969", dodgerblue:"1e90ff", firebrick:"b22222", floralwhite:"fffaf0", forestgreen:"228b22", fuchsia:"f0f", gainsboro:"dcdcdc", ghostwhite:"f8f8ff", gold:"ffd700", goldenrod:"daa520", gray:"808080", green:"008000", greenyellow:"adff2f", grey:"808080", honeydew:"f0fff0", hotpink:"ff69b4", indianred:"cd5c5c", indigo:"4b0082", ivory:"fffff0", khaki:"f0e68c", lavender:"e6e6fa", lavenderblush:"fff0f5", lawngreen:"7cfc00", lemonchiffon:"fffacd", lightblue:"add8e6", lightcoral:"f08080", lightcyan:"e0ffff", lightgoldenrodyellow:"fafad2", lightgray:"d3d3d3", lightgreen:"90ee90", lightgrey:"d3d3d3", lightpink:"ffb6c1", lightsalmon:"ffa07a", lightseagreen:"20b2aa", lightskyblue:"87cefa", lightslategray:"789", lightslategrey:"789", lightsteelblue:"b0c4de", lightyellow:"ffffe0", lime:"0f0", limegreen:"32cd32", linen:"faf0e6", magenta:"f0f", maroon:"800000", mediumaquamarine:"66cdaa", mediumblue:"0000cd", mediumorchid:"ba55d3", mediumpurple:"9370db", mediumseagreen:"3cb371", mediumslateblue:"7b68ee", mediumspringgreen:"00fa9a", mediumturquoise:"48d1cc", mediumvioletred:"c71585", midnightblue:"191970", mintcream:"f5fffa", mistyrose:"ffe4e1", moccasin:"ffe4b5", navajowhite:"ffdead", navy:"000080", oldlace:"fdf5e6", olive:"808000", olivedrab:"6b8e23", orange:"ffa500", orangered:"ff4500", orchid:"da70d6", palegoldenrod:"eee8aa", palegreen:"98fb98", paleturquoise:"afeeee", palevioletred:"db7093", papayawhip:"ffefd5", peachpuff:"ffdab9", peru:"cd853f", pink:"ffc0cb", plum:"dda0dd", powderblue:"b0e0e6", purple:"800080", rebeccapurple:"663399", red:"f00", rosybrown:"bc8f8f", royalblue:"4169e1", saddlebrown:"8b4513", salmon:"fa8072", sandybrown:"f4a460", seagreen:"2e8b57", seashell:"fff5ee", sienna:"a0522d", silver:"c0c0c0", skyblue:"87ceeb", slateblue:"6a5acd", slategray:"708090", slategrey:"708090", snow:"fffafa", springgreen:"00ff7f", steelblue:"4682b4", tan:"d2b48c", teal:"008080", thistle:"d8bfd8", tomato:"ff6347", turquoise:"40e0d0", violet:"ee82ee", wheat:"f5deb3", white:"fff", whitesmoke:"f5f5f5", yellow:"ff0", yellowgreen:"9acd32"}; function boundAlpha(a){ a=parseFloat(a); if(isNaN(a)||a<0||a>1){ a=1;} return a;} function bound01(n,max){ if(isOnePointZero(n)){n="100%";} var processPercent=isPercentage(n); n=mathMin(max,mathMax(0,parseFloat(n))); if(processPercent){ n=parseInt(n*max,10)/100;} if(Math.abs(n-max)<0.000001){ return 1;} return n%max/parseFloat(max);} function parseIntFromHex(val){ return parseInt(val,16);} function isOnePointZero(n){ return typeof n=="string"&&n.indexOf('.')!=-1&&parseFloat(n)===1;} function isPercentage(n){ return typeof n==="string"&&n.indexOf('%')!=-1;} function convertToPercentage(n){ if(n<=1){ n=n*100+"%";} return n;} function convertHexToDecimal(h){ return parseIntFromHex(h)/255;} var matchers=(function(){ var CSS_INTEGER="[-\\+]?\\d+%?"; var CSS_NUMBER="[-\\+]?\\d*\\.\\d+%?"; var CSS_UNIT="(?:"+CSS_NUMBER+")|(?:"+CSS_INTEGER+")"; var PERMISSIVE_MATCH3="[\\s|\\(]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")\\s*\\)?"; var PERMISSIVE_MATCH4="[\\s|\\(]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")[,|\\s]+("+CSS_UNIT+")\\s*\\)?"; return { rgb:new RegExp("rgb"+PERMISSIVE_MATCH3), rgba:new RegExp("rgba"+PERMISSIVE_MATCH4), hsl:new RegExp("hsl"+PERMISSIVE_MATCH3), hsla:new RegExp("hsla"+PERMISSIVE_MATCH4), hsv:new RegExp("hsv"+PERMISSIVE_MATCH3), hsva:new RegExp("hsva"+PERMISSIVE_MATCH4), hex3:/^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex4:/^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, hex6:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, hex8:/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/};})(); function stringInputToObject(color){ color=color.replace(trimLeft,'').replace(trimRight,'').toLowerCase(); var named=false; if(names[color]){ color=names[color]; named=true;}else if(color=='transparent'){ return {r:0,g:0,b:0,a:0,format:"name"};} var match; if(match=matchers.rgb.exec(color)){ return {r:match[1],g:match[2],b:match[3]};} if(match=matchers.rgba.exec(color)){ return {r:match[1],g:match[2],b:match[3],a:match[4]};} if(match=matchers.hsl.exec(color)){ return {h:match[1],s:match[2],l:match[3]};} if(match=matchers.hsla.exec(color)){ return {h:match[1],s:match[2],l:match[3],a:match[4]};} if(match=matchers.hsv.exec(color)){ return {h:match[1],s:match[2],v:match[3]};} if(match=matchers.hsva.exec(color)){ return {h:match[1],s:match[2],v:match[3],a:match[4]};} if(match=matchers.hex8.exec(color)){ return { r:parseIntFromHex(match[1]), g:parseIntFromHex(match[2]), b:parseIntFromHex(match[3]), a:convertHexToDecimal(match[4]), format:named?"name":"hex"};} if(match=matchers.hex6.exec(color)){ return { r:parseIntFromHex(match[1]), g:parseIntFromHex(match[2]), b:parseIntFromHex(match[3]), format:named?"name":"hex"};} if(match=matchers.hex4.exec(color)){ return { r:parseIntFromHex(match[1]+''+match[1]), g:parseIntFromHex(match[2]+''+match[2]), b:parseIntFromHex(match[3]+''+match[3]), a:convertHexToDecimal(match[4]+''+match[4]), format:named?"name":"hex"};} if(match=matchers.hex3.exec(color)){ return { r:parseIntFromHex(match[1]+''+match[1]), g:parseIntFromHex(match[2]+''+match[2]), b:parseIntFromHex(match[3]+''+match[3]), format:named?"name":"hex"};} return false;} module.exports=tinycolor; }); __d('processTransform',function(global, require, module, exports) { 'use strict'; var MatrixMath=require('MatrixMath'); var Platform=require('Platform'); var invariant=require('invariant'); var stringifySafe=require('stringifySafe'); function processTransform(transform){ var result=MatrixMath.createIdentityMatrix(); transform.forEach(function(transformation){ var key=Object.keys(transformation)[0]; var value=transformation[key]; if(__DEV__){ _validateTransform(key,value,transformation);} switch(key){ case 'matrix': MatrixMath.multiplyInto(result,result,value); break; case 'perspective': _multiplyTransform(result,MatrixMath.reusePerspectiveCommand,[value]); break; case 'rotateX': _multiplyTransform(result,MatrixMath.reuseRotateXCommand,[_convertToRadians(value)]); break; case 'rotateY': _multiplyTransform(result,MatrixMath.reuseRotateYCommand,[_convertToRadians(value)]); break; case 'rotate': case 'rotateZ': _multiplyTransform(result,MatrixMath.reuseRotateZCommand,[_convertToRadians(value)]); break; case 'scale': _multiplyTransform(result,MatrixMath.reuseScaleCommand,[value]); break; case 'scaleX': _multiplyTransform(result,MatrixMath.reuseScaleXCommand,[value]); break; case 'scaleY': _multiplyTransform(result,MatrixMath.reuseScaleYCommand,[value]); break; case 'translate': _multiplyTransform(result,MatrixMath.reuseTranslate3dCommand,[value[0],value[1],value[2]||0]); break; case 'translateX': _multiplyTransform(result,MatrixMath.reuseTranslate2dCommand,[value,0]); break; case 'translateY': _multiplyTransform(result,MatrixMath.reuseTranslate2dCommand,[0,value]); break; case 'skewX': _multiplyTransform(result,MatrixMath.reuseSkewXCommand,[_convertToRadians(value)]); break; case 'skewY': _multiplyTransform(result,MatrixMath.reuseSkewYCommand,[_convertToRadians(value)]); break; default: throw new Error('Invalid transform name: '+key);}}); if(Platform.OS==='android'){ return MatrixMath.decomposeMatrix(result);} return result;} function _multiplyTransform( result, matrixMathFunction, args) { var matrixToApply=MatrixMath.createIdentityMatrix(); var argsWithIdentity=[matrixToApply].concat(args); matrixMathFunction.apply(this,argsWithIdentity); MatrixMath.multiplyInto(result,result,matrixToApply);} function _convertToRadians(value){ var floatValue=parseFloat(value,10); return value.indexOf('rad')>-1?floatValue:floatValue*Math.PI/180;} function _validateTransform(key,value,transformation){ invariant( !value.getValue, 'You passed an Animated.Value to a normal component. '+ 'You need to wrap that component in an Animated. For example, '+ 'replace by .'); var multivalueTransforms=[ 'matrix', 'translate']; if(multivalueTransforms.indexOf(key)!==-1){ invariant( Array.isArray(value), 'Transform with key of %s must have an array as the value: %s', key, stringifySafe(transformation));} switch(key){ case 'matrix': invariant( value.length===9||value.length===16, 'Matrix transform must have a length of 9 (2d) or 16 (3d). '+ 'Provided matrix has a length of %s: %s', value.length, stringifySafe(transformation)); break; case 'translate': break; case 'rotateX': case 'rotateY': case 'rotateZ': case 'rotate': case 'skewX': case 'skewY': invariant( typeof value==='string', 'Transform with key of "%s" must be a string: %s', key, stringifySafe(transformation)); invariant( value.indexOf('deg')>-1||value.indexOf('rad')>-1, 'Rotate transform must be expressed in degrees (deg) or radians '+ '(rad): %s', stringifySafe(transformation)); break; default: invariant( typeof value==='number', 'Transform with key of "%s" must be a number: %s', key, stringifySafe(transformation));}} module.exports=processTransform; }); __d('MatrixMath',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var MatrixMath={ createIdentityMatrix:function(){ return [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];}, createCopy:function(m){ return [ m[0],m[1],m[2],m[3], m[4],m[5],m[6],m[7], m[8],m[9],m[10],m[11], m[12],m[13],m[14],m[15]];}, createOrthographic:function(left,right,bottom,top,near,far){ var a=2/(right-left); var b=2/(top-bottom); var c=-2/(far-near); var tx=-(right+left)/(right-left); var ty=-(top+bottom)/(top-bottom); var tz=-(far+near)/(far-near); return [ a,0,0,0, 0,b,0,0, 0,0,c,0, tx,ty,tz,1];}, createFrustum:function(left,right,bottom,top,near,far){ var r_width=1/(right-left); var r_height=1/(top-bottom); var r_depth=1/(near-far); var x=2*(near*r_width); var y=2*(near*r_height); var A=(right+left)*r_width; var B=(top+bottom)*r_height; var C=(far+near)*r_depth; var D=2*(far*near*r_depth); return [ x,0,0,0, 0,y,0,0, A,B,C,-1, 0,0,D,0];}, createPerspective:function(fovInRadians,aspect,near,far){ var h=1/Math.tan(fovInRadians); var r_depth=1/(near-far); var C=(far+near)*r_depth; var D=2*(far*near*r_depth); return [ h/aspect,0,0,0, 0,h,0,0, 0,0,C,-1, 0,0,D,0];}, createTranslate2d:function(x,y){ var mat=MatrixMath.createIdentityMatrix(); MatrixMath.reuseTranslate2dCommand(mat,x,y); return mat;}, reuseTranslate2dCommand:function(matrixCommand,x,y){ matrixCommand[12]=x; matrixCommand[13]=y;}, reuseTranslate3dCommand:function(matrixCommand,x,y,z){ matrixCommand[12]=x; matrixCommand[13]=y; matrixCommand[14]=z;}, createScale:function(factor){ var mat=MatrixMath.createIdentityMatrix(); MatrixMath.reuseScaleCommand(mat,factor); return mat;}, reuseScaleCommand:function(matrixCommand,factor){ matrixCommand[0]=factor; matrixCommand[5]=factor;}, reuseScale3dCommand:function(matrixCommand,x,y,z){ matrixCommand[0]=x; matrixCommand[5]=y; matrixCommand[10]=z;}, reusePerspectiveCommand:function(matrixCommand,p){ matrixCommand[11]=-1/p;}, reuseScaleXCommand:function(matrixCommand,factor){ matrixCommand[0]=factor;}, reuseScaleYCommand:function(matrixCommand,factor){ matrixCommand[5]=factor;}, reuseScaleZCommand:function(matrixCommand,factor){ matrixCommand[10]=factor;}, reuseRotateXCommand:function(matrixCommand,radians){ matrixCommand[5]=Math.cos(radians); matrixCommand[6]=Math.sin(radians); matrixCommand[9]=-Math.sin(radians); matrixCommand[10]=Math.cos(radians);}, reuseRotateYCommand:function(matrixCommand,amount){ matrixCommand[0]=Math.cos(amount); matrixCommand[2]=-Math.sin(amount); matrixCommand[8]=Math.sin(amount); matrixCommand[10]=Math.cos(amount);}, reuseRotateZCommand:function(matrixCommand,radians){ matrixCommand[0]=Math.cos(radians); matrixCommand[1]=Math.sin(radians); matrixCommand[4]=-Math.sin(radians); matrixCommand[5]=Math.cos(radians);}, createRotateZ:function(radians){ var mat=MatrixMath.createIdentityMatrix(); MatrixMath.reuseRotateZCommand(mat,radians); return mat;}, reuseSkewXCommand:function(matrixCommand,radians){ matrixCommand[4]=Math.sin(radians); matrixCommand[5]=Math.cos(radians);}, reuseSkewYCommand:function(matrixCommand,radians){ matrixCommand[0]=Math.cos(radians); matrixCommand[1]=Math.sin(radians);}, multiplyInto:function(out,a,b){ var a00=a[0],a01=a[1],a02=a[2],a03=a[3], a10=a[4],a11=a[5],a12=a[6],a13=a[7], a20=a[8],a21=a[9],a22=a[10],a23=a[11], a30=a[12],a31=a[13],a32=a[14],a33=a[15]; var b0=b[0],b1=b[1],b2=b[2],b3=b[3]; out[0]=b0*a00+b1*a10+b2*a20+b3*a30; out[1]=b0*a01+b1*a11+b2*a21+b3*a31; out[2]=b0*a02+b1*a12+b2*a22+b3*a32; out[3]=b0*a03+b1*a13+b2*a23+b3*a33; b0=b[4];b1=b[5];b2=b[6];b3=b[7]; out[4]=b0*a00+b1*a10+b2*a20+b3*a30; out[5]=b0*a01+b1*a11+b2*a21+b3*a31; out[6]=b0*a02+b1*a12+b2*a22+b3*a32; out[7]=b0*a03+b1*a13+b2*a23+b3*a33; b0=b[8];b1=b[9];b2=b[10];b3=b[11]; out[8]=b0*a00+b1*a10+b2*a20+b3*a30; out[9]=b0*a01+b1*a11+b2*a21+b3*a31; out[10]=b0*a02+b1*a12+b2*a22+b3*a32; out[11]=b0*a03+b1*a13+b2*a23+b3*a33; b0=b[12];b1=b[13];b2=b[14];b3=b[15]; out[12]=b0*a00+b1*a10+b2*a20+b3*a30; out[13]=b0*a01+b1*a11+b2*a21+b3*a31; out[14]=b0*a02+b1*a12+b2*a22+b3*a32; out[15]=b0*a03+b1*a13+b2*a23+b3*a33;}, determinant:function(matrix){var _matrix=babelHelpers.slicedToArray( matrix,16);var m00=_matrix[0];var m01=_matrix[1];var m02=_matrix[2];var m03=_matrix[3];var m10=_matrix[4];var m11=_matrix[5];var m12=_matrix[6];var m13=_matrix[7];var m20=_matrix[8];var m21=_matrix[9];var m22=_matrix[10];var m23=_matrix[11];var m30=_matrix[12];var m31=_matrix[13];var m32=_matrix[14];var m33=_matrix[15]; return ( m03*m12*m21*m30-m02*m13*m21*m30- m03*m11*m22*m30+m01*m13*m22*m30+ m02*m11*m23*m30-m01*m12*m23*m30- m03*m12*m20*m31+m02*m13*m20*m31+ m03*m10*m22*m31-m00*m13*m22*m31- m02*m10*m23*m31+m00*m12*m23*m31+ m03*m11*m20*m32-m01*m13*m20*m32- m03*m10*m21*m32+m00*m13*m21*m32+ m01*m10*m23*m32-m00*m11*m23*m32- m02*m11*m20*m33+m01*m12*m20*m33+ m02*m10*m21*m33-m00*m12*m21*m33- m01*m10*m22*m33+m00*m11*m22*m33);}, inverse:function(matrix){ var det=MatrixMath.determinant(matrix); if(!det){ return matrix;}var _matrix2=babelHelpers.slicedToArray( matrix,16);var m00=_matrix2[0];var m01=_matrix2[1];var m02=_matrix2[2];var m03=_matrix2[3];var m10=_matrix2[4];var m11=_matrix2[5];var m12=_matrix2[6];var m13=_matrix2[7];var m20=_matrix2[8];var m21=_matrix2[9];var m22=_matrix2[10];var m23=_matrix2[11];var m30=_matrix2[12];var m31=_matrix2[13];var m32=_matrix2[14];var m33=_matrix2[15]; return [ (m12*m23*m31-m13*m22*m31+m13*m21*m32-m11*m23*m32-m12*m21*m33+m11*m22*m33)/det, (m03*m22*m31-m02*m23*m31-m03*m21*m32+m01*m23*m32+m02*m21*m33-m01*m22*m33)/det, (m02*m13*m31-m03*m12*m31+m03*m11*m32-m01*m13*m32-m02*m11*m33+m01*m12*m33)/det, (m03*m12*m21-m02*m13*m21-m03*m11*m22+m01*m13*m22+m02*m11*m23-m01*m12*m23)/det, (m13*m22*m30-m12*m23*m30-m13*m20*m32+m10*m23*m32+m12*m20*m33-m10*m22*m33)/det, (m02*m23*m30-m03*m22*m30+m03*m20*m32-m00*m23*m32-m02*m20*m33+m00*m22*m33)/det, (m03*m12*m30-m02*m13*m30-m03*m10*m32+m00*m13*m32+m02*m10*m33-m00*m12*m33)/det, (m02*m13*m20-m03*m12*m20+m03*m10*m22-m00*m13*m22-m02*m10*m23+m00*m12*m23)/det, (m11*m23*m30-m13*m21*m30+m13*m20*m31-m10*m23*m31-m11*m20*m33+m10*m21*m33)/det, (m03*m21*m30-m01*m23*m30-m03*m20*m31+m00*m23*m31+m01*m20*m33-m00*m21*m33)/det, (m01*m13*m30-m03*m11*m30+m03*m10*m31-m00*m13*m31-m01*m10*m33+m00*m11*m33)/det, (m03*m11*m20-m01*m13*m20-m03*m10*m21+m00*m13*m21+m01*m10*m23-m00*m11*m23)/det, (m12*m21*m30-m11*m22*m30-m12*m20*m31+m10*m22*m31+m11*m20*m32-m10*m21*m32)/det, (m01*m22*m30-m02*m21*m30+m02*m20*m31-m00*m22*m31-m01*m20*m32+m00*m21*m32)/det, (m02*m11*m30-m01*m12*m30-m02*m10*m31+m00*m12*m31+m01*m10*m32-m00*m11*m32)/det, (m01*m12*m20-m02*m11*m20+m02*m10*m21-m00*m12*m21-m01*m10*m22+m00*m11*m22)/det];}, transpose:function(m){ return [ m[0],m[4],m[8],m[12], m[1],m[5],m[9],m[13], m[2],m[6],m[10],m[14], m[3],m[7],m[11],m[15]];}, multiplyVectorByMatrix:function( v, m) {var _v=babelHelpers.slicedToArray( v,4);var vx=_v[0];var vy=_v[1];var vz=_v[2];var vw=_v[3]; return [ vx*m[0]+vy*m[4]+vz*m[8]+vw*m[12], vx*m[1]+vy*m[5]+vz*m[9]+vw*m[13], vx*m[2]+vy*m[6]+vz*m[10]+vw*m[14], vx*m[3]+vy*m[7]+vz*m[11]+vw*m[15]];}, v3Length:function(a){ return Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]);}, v3Normalize:function( vector, v3Length) { var im=1/(v3Length||MatrixMath.v3Length(vector)); return [ vector[0]*im, vector[1]*im, vector[2]*im];}, v3Dot:function(a,b){ return a[0]*b[0]+ a[1]*b[1]+ a[2]*b[2];}, v3Combine:function( a, b, aScale, bScale) { return [ aScale*a[0]+bScale*b[0], aScale*a[1]+bScale*b[1], aScale*a[2]+bScale*b[2]];}, v3Cross:function(a,b){ return [ a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]];}, quaternionToDegreesXYZ:function(q,matrix,row){var _q=babelHelpers.slicedToArray( q,4);var qx=_q[0];var qy=_q[1];var qz=_q[2];var qw=_q[3]; var qw2=qw*qw; var qx2=qx*qx; var qy2=qy*qy; var qz2=qz*qz; var test=qx*qy+qz*qw; var unit=qw2+qx2+qy2+qz2; var conv=180/Math.PI; if(test>0.49999*unit){ return [0,2*Math.atan2(qx,qw)*conv,90];} if(test<-0.49999*unit){ return [0,-2*Math.atan2(qx,qw)*conv,-90];} return [ MatrixMath.roundTo3Places( Math.atan2(2*qx*qw-2*qy*qz,1-2*qx2-2*qz2)*conv), MatrixMath.roundTo3Places( Math.atan2(2*qy*qw-2*qx*qz,1-2*qy2-2*qz2)*conv), MatrixMath.roundTo3Places( Math.asin(2*qx*qy+2*qz*qw)*conv)];}, roundTo3Places:function(n){ var arr=n.toString().split('e'); return Math.round(arr[0]+'e'+(arr[1]?+arr[1]-3:3))*0.001;}, decomposeMatrix:function(transformMatrix){ invariant( transformMatrix.length===16, 'Matrix decomposition needs a list of 3d matrix values, received %s', transformMatrix); var perspective=[]; var quaternion=[]; var scale=[]; var skew=[]; var translation=[]; if(!transformMatrix[15]){ return;} var matrix=[]; var perspectiveMatrix=[]; for(var i=0;i<4;i++){ matrix.push([]); for(var j=0;j<4;j++){ var value=transformMatrix[i*4+j]/transformMatrix[15]; matrix[i].push(value); perspectiveMatrix.push(j===3?0:value);}} perspectiveMatrix[15]=1; if(!MatrixMath.determinant(perspectiveMatrix)){ return;} if(matrix[0][3]!==0||matrix[1][3]!==0||matrix[2][3]!==0){ var rightHandSide=[ matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]]; var inversePerspectiveMatrix=MatrixMath.inverse3x3( perspectiveMatrix); var transposedInversePerspectiveMatrix=MatrixMath.transpose4x4( inversePerspectiveMatrix); var perspective=MatrixMath.multiplyVectorByMatrix( rightHandSide, transposedInversePerspectiveMatrix);}else { perspective[0]=perspective[1]=perspective[2]=0; perspective[3]=1;} for(var i=0;i<3;i++){ translation[i]=matrix[3][i];} var row=[]; for(i=0;i<3;i++){ row[i]=[ matrix[i][0], matrix[i][1], matrix[i][2]];} scale[0]=MatrixMath.v3Length(row[0]); row[0]=MatrixMath.v3Normalize(row[0],scale[0]); skew[0]=MatrixMath.v3Dot(row[0],row[1]); row[1]=MatrixMath.v3Combine(row[1],row[0],1.0,-skew[0]); skew[0]=MatrixMath.v3Dot(row[0],row[1]); row[1]=MatrixMath.v3Combine(row[1],row[0],1.0,-skew[0]); scale[1]=MatrixMath.v3Length(row[1]); row[1]=MatrixMath.v3Normalize(row[1],scale[1]); skew[0]/=scale[1]; skew[1]=MatrixMath.v3Dot(row[0],row[2]); row[2]=MatrixMath.v3Combine(row[2],row[0],1.0,-skew[1]); skew[2]=MatrixMath.v3Dot(row[1],row[2]); row[2]=MatrixMath.v3Combine(row[2],row[1],1.0,-skew[2]); scale[2]=MatrixMath.v3Length(row[2]); row[2]=MatrixMath.v3Normalize(row[2],scale[2]); skew[1]/=scale[2]; skew[2]/=scale[2]; var pdum3=MatrixMath.v3Cross(row[1],row[2]); if(MatrixMath.v3Dot(row[0],pdum3)<0){ for(i=0;i<3;i++){ scale[i]*=-1; row[i][0]*=-1; row[i][1]*=-1; row[i][2]*=-1;}} quaternion[0]= 0.5*Math.sqrt(Math.max(1+row[0][0]-row[1][1]-row[2][2],0)); quaternion[1]= 0.5*Math.sqrt(Math.max(1-row[0][0]+row[1][1]-row[2][2],0)); quaternion[2]= 0.5*Math.sqrt(Math.max(1-row[0][0]-row[1][1]+row[2][2],0)); quaternion[3]= 0.5*Math.sqrt(Math.max(1+row[0][0]+row[1][1]+row[2][2],0)); if(row[2][1]>row[1][2]){ quaternion[0]=-quaternion[0];} if(row[0][2]>row[2][0]){ quaternion[1]=-quaternion[1];} if(row[1][0]>row[0][1]){ quaternion[2]=-quaternion[2];} var rotationDegrees; if( quaternion[0]<0.001&&quaternion[0]>=0&& quaternion[1]<0.001&&quaternion[1]>=0) { rotationDegrees=[0,0,MatrixMath.roundTo3Places( Math.atan2(row[0][1],row[0][0])*180/Math.PI)];}else { rotationDegrees=MatrixMath.quaternionToDegreesXYZ(quaternion,matrix,row);} return { rotationDegrees:rotationDegrees, perspective:perspective, quaternion:quaternion, scale:scale, skew:skew, translation:translation, rotate:rotationDegrees[2], scaleX:scale[0], scaleY:scale[1], translateX:translation[0], translateY:translation[1]};}}; module.exports=MatrixMath; }); __d('sizesDiffer',function(global, require, module, exports) { 'use strict'; var dummySize={width:undefined,height:undefined}; var sizesDiffer=function(one,two){ one=one||dummySize; two=two||dummySize; return one!==two&&( one.width!==two.width|| one.height!==two.height);}; module.exports=sizesDiffer; }); __d('ReactMultiChild',function(global, require, module, exports) { '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'); var updateDepth=0; var updateQueue=[]; var markupQueue=[]; function enqueueInsertMarkup(parentID,markup,toIndex){ updateQueue.push({ parentID:parentID, parentNode:null, type:ReactMultiChildUpdateTypes.INSERT_MARKUP, markupIndex:markupQueue.push(markup)-1, content:null, fromIndex:null, toIndex:toIndex});} function enqueueMove(parentID,fromIndex,toIndex){ updateQueue.push({ parentID:parentID, parentNode:null, type:ReactMultiChildUpdateTypes.MOVE_EXISTING, markupIndex:null, content:null, fromIndex:fromIndex, toIndex:toIndex});} function enqueueRemove(parentID,fromIndex){ updateQueue.push({ parentID:parentID, parentNode:null, type:ReactMultiChildUpdateTypes.REMOVE_NODE, markupIndex:null, content:null, fromIndex:fromIndex, toIndex:null});} function enqueueSetMarkup(parentID,markup){ updateQueue.push({ parentID:parentID, parentNode:null, type:ReactMultiChildUpdateTypes.SET_MARKUP, markupIndex:null, content:markup, fromIndex:null, toIndex:null});} function enqueueTextContent(parentID,textContent){ updateQueue.push({ parentID:parentID, parentNode:null, type:ReactMultiChildUpdateTypes.TEXT_CONTENT, markupIndex:null, content:textContent, fromIndex:null, toIndex:null});} function processQueue(){ if(updateQueue.length){ ReactComponentEnvironment.processChildrenUpdates( updateQueue, markupQueue); clearQueue();}} function clearQueue(){ updateQueue.length=0; markupQueue.length=0;} var ReactMultiChild={ Mixin:{ _reconcilerInstantiateChildren:function(nestedChildren,transaction,context){ if(__DEV__){ 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(__DEV__){ 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);}, 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]; var rootID=this._rootNodeID+name; var mountImage=ReactReconciler.mountComponent( child, rootID, transaction, context); child._mountIndex=index++; mountImages.push(mountImage);}} return mountImages;}, updateTextContent:function(nextContent){ updateDepth++; var errorThrown=true; try{ var prevChildren=this._renderedChildren; ReactChildReconciler.unmountChildren(prevChildren); for(var name in prevChildren){ if(prevChildren.hasOwnProperty(name)){ this._unmountChild(prevChildren[name]);}} this.setTextContent(nextContent); errorThrown=false;}finally { updateDepth--; if(!updateDepth){ if(errorThrown){ clearQueue();}else { processQueue();}}}}, updateMarkup:function(nextMarkup){ updateDepth++; var errorThrown=true; try{ var prevChildren=this._renderedChildren; 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();}}}}, 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();}}}}, _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; 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){ lastIndex=Math.max(prevChild._mountIndex,lastIndex); this._unmountChild(prevChild);} this._mountChildByNameAtIndex( nextChild,name,nextIndex,transaction,context);} nextIndex++;} for(name in prevChildren){ if(prevChildren.hasOwnProperty(name)&& !(nextChildren&&nextChildren.hasOwnProperty(name))){ this._unmountChild(prevChildren[name]);}}}, unmountChildren:function(){ var renderedChildren=this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren); this._renderedChildren=null;}, moveChild:function(child,toIndex,lastIndex){ if(child._mountIndex1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];} if(newThis!==component&&newThis!==null){ warning( false, 'bind(): React component methods may only be bound to the '+ 'component instance. See %s', componentName);}else if(!args.length){ 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); return boundMethod;} var reboundMethod=_bind.apply(boundMethod,arguments); reboundMethod.__reactBoundContext=component; reboundMethod.__reactBoundMethod=method; reboundMethod.__reactBoundArguments=args; return reboundMethod;};} return boundMethod;} function bindAutoBindMethods(component){ for(var autoBindKey in component.__reactAutoBindMap){ if(component.__reactAutoBindMap.hasOwnProperty(autoBindKey)){ var method=component.__reactAutoBindMap[autoBindKey]; component[autoBindKey]=bindAutoBindMethod( component, method);}}} var ReactClassMixin={ replaceState:function(newState,callback){ this.updater.enqueueReplaceState(this,newState); if(callback){ this.updater.enqueueCallback(this,callback);}}, isMounted:function(){ return this.updater.isMounted(this);}, setProps:function(partialProps,callback){ if(__DEV__){ warnSetProps();} this.updater.enqueueSetProps(this,partialProps); if(callback){ this.updater.enqueueCallback(this,callback);}}, replaceProps:function(newProps,callback){ if(__DEV__){ warnSetProps();} this.updater.enqueueReplaceProps(this,newProps); if(callback){ this.updater.enqueueCallback(this,callback);}}}; var ReactClassComponent=function(){}; assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); var ReactClass={ createClass:function(spec){ var Constructor=function(props,context,updater){ if(__DEV__){ warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or '+ 'JSX instead. See: https://fb.me/react-legacyfactory');} if(this.__reactAutoBindMap){ bindAutoBindMethods(this);} this.props=props; this.context=context; this.refs=emptyObject; this.updater=updater||ReactNoopUpdateQueue; this.state=null; var initialState=this.getInitialState?this.getInitialState():null; if(__DEV__){ if(typeof initialState==='undefined'&& this.getInitialState._isMockFunction){ initialState=null;}} invariant( typeof initialState==='object'&&!Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName||'ReactCompositeComponent'); this.state=initialState;}; Constructor.prototype=new ReactClassComponent(); Constructor.prototype.constructor=Constructor; injectedMixins.forEach( mixSpecIntoComponent.bind(null,Constructor)); mixSpecIntoComponent(Constructor,spec); if(Constructor.getDefaultProps){ Constructor.defaultProps=Constructor.getDefaultProps();} if(__DEV__){ if(Constructor.getDefaultProps){ Constructor.getDefaultProps.isReactClassApproved={};} if(Constructor.prototype.getInitialState){ Constructor.prototype.getInitialState.isReactClassApproved={};}} invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.'); if(__DEV__){ 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'); warning( !Constructor.prototype.componentWillRecieveProps, '%s has a method called '+ 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName||'A component');} 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; }); __d('ReactComponent',function(global, require, module, exports) { 'use strict'; var ReactNoopUpdateQueue=require('ReactNoopUpdateQueue'); var canDefineProperty=require('canDefineProperty'); var emptyObject=require('emptyObject'); var invariant=require('invariant'); var warning=require('warning'); function ReactComponent(props,context,updater){ this.props=props; this.context=context; this.refs=emptyObject; this.updater=updater||ReactNoopUpdateQueue;} ReactComponent.prototype.isReactComponent={}; ReactComponent.prototype.setState=function(partialState,callback){ invariant( typeof partialState==='object'|| typeof partialState==='function'|| partialState==null, 'setState(...): takes an object of state variables to update or a '+ 'function which returns an object of state variables.'); if(__DEV__){ warning( partialState!=null, 'setState(...): You passed an undefined or null state object; '+ 'instead, use forceUpdate().');} this.updater.enqueueSetState(this,partialState); if(callback){ this.updater.enqueueCallback(this,callback);}}; ReactComponent.prototype.forceUpdate=function(callback){ this.updater.enqueueForceUpdate(this); if(callback){ this.updater.enqueueCallback(this,callback);}}; if(__DEV__){ 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(){ warning( false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined;}});}}; for(var fnName in deprecatedAPIs){ if(deprecatedAPIs.hasOwnProperty(fnName)){ defineDeprecationWarning(fnName,deprecatedAPIs[fnName]);}}} module.exports=ReactComponent; }); __d('ReactNoopUpdateQueue',function(global, require, module, exports) { 'use strict'; var warning=require('warning'); function warnTDZ(publicInstance,callerName){ if(__DEV__){ 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||'');}} var ReactNoopUpdateQueue={ isMounted:function(publicInstance){ return false;}, enqueueCallback:function(publicInstance,callback){}, enqueueForceUpdate:function(publicInstance){ warnTDZ(publicInstance,'forceUpdate');}, enqueueReplaceState:function(publicInstance,completeState){ warnTDZ(publicInstance,'replaceState');}, enqueueSetState:function(publicInstance,partialState){ warnTDZ(publicInstance,'setState');}, enqueueSetProps:function(publicInstance,partialProps){ warnTDZ(publicInstance,'setProps');}, enqueueReplaceProps:function(publicInstance,props){ warnTDZ(publicInstance,'replaceProps');}}; module.exports=ReactNoopUpdateQueue; }); __d('ReactElementValidator',function(global, require, module, exports) { '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('invariant'); var warning=require('warning'); function getDeclarationErrorAddendum(){ if(ReactCurrentOwner.current){ var name=ReactCurrentOwner.current.getName(); if(name){ return ' Check the render method of `'+name+'`.';}} return '';} var ownerHasKeyUseWarning={}; var loggedTypeFailures={}; 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){ return;} warning( false, 'Each child in an array or iterator should have a unique "key" prop.'+ '%s%s%s', addenda.parentOrOwner||'', addenda.childOwner||'', addenda.url||'');} 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}; if(element&& element._owner&& element._owner!==ReactCurrentOwner.current){ addenda.childOwner=' It was passed a child from '+ element._owner.getName()+'.';} return addenda;} function validateChildKeys(node,parentType){ if(typeof node!=='object'){ return;} if(Array.isArray(node)){ for(var i=0;i>')+': '+ JSON.stringify(style,null,' ')+(message2||''));}; var allStylePropTypes={}; StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes); StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes); StyleSheetValidation.addValidStylePropTypes(ViewStylePropTypes); module.exports=StyleSheetValidation; }); __d('View',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var PropTypes=require('ReactPropTypes'); var RCTUIManager=require('NativeModules').UIManager; var React=require('React'); var ReactNativeStyleAttributes=require('ReactNativeStyleAttributes'); var ReactNativeViewAttributes=require('ReactNativeViewAttributes'); var StyleSheetPropType=require('StyleSheetPropType'); var ViewStylePropTypes=require('ViewStylePropTypes'); var requireNativeComponent=require('requireNativeComponent'); var stylePropType=StyleSheetPropType(ViewStylePropTypes); var AccessibilityTraits=[ 'none', 'button', 'link', 'header', 'search', 'image', 'selected', 'plays', 'key', 'text', 'summary', 'disabled', 'frequentUpdates', 'startsMedia', 'adjustable', 'allowsDirectInteraction', 'pageTurn']; var AccessibilityComponentType=[ 'none', 'button', 'radiobutton_checked', 'radiobutton_unchecked']; var View=React.createClass({displayName:'View', mixins:[NativeMethodsMixin], viewConfig:{ uiViewClassName:'RCTView', validAttributes:ReactNativeViewAttributes.RCTView}, statics:{ AccessibilityTraits:AccessibilityTraits, AccessibilityComponentType:AccessibilityComponentType}, propTypes:{ accessible:PropTypes.bool, accessibilityLabel:PropTypes.string, accessibilityComponentType:PropTypes.oneOf(AccessibilityComponentType), accessibilityLiveRegion:PropTypes.oneOf([ 'none', 'polite', 'assertive']), importantForAccessibility:PropTypes.oneOf([ 'auto', 'yes', 'no', 'no-hide-descendants']), accessibilityTraits:PropTypes.oneOfType([ PropTypes.oneOf(AccessibilityTraits), PropTypes.arrayOf(PropTypes.oneOf(AccessibilityTraits))]), onAccessibilityTap:PropTypes.func, onMagicTap:PropTypes.func, testID:PropTypes.string, onResponderGrant:PropTypes.func, onResponderMove:PropTypes.func, onResponderReject:PropTypes.func, onResponderRelease:PropTypes.func, onResponderTerminate:PropTypes.func, onResponderTerminationRequest:PropTypes.func, onStartShouldSetResponder:PropTypes.func, onStartShouldSetResponderCapture:PropTypes.func, onMoveShouldSetResponder:PropTypes.func, onMoveShouldSetResponderCapture:PropTypes.func, onLayout:PropTypes.func, pointerEvents:PropTypes.oneOf([ 'box-none', 'none', 'box-only', 'auto']), style:stylePropType, removeClippedSubviews:PropTypes.bool, renderToHardwareTextureAndroid:PropTypes.bool, shouldRasterizeIOS:PropTypes.bool, collapsable:PropTypes.bool, needsOffscreenAlphaCompositing:PropTypes.bool}, render:function(){ return React.createElement(RCTView,this.props);}}); var RCTView=requireNativeComponent('RCTView',View,{ nativeOnly:{ nativeBackgroundAndroid:true}}); if(__DEV__){ var viewConfig=RCTUIManager.viewConfigs&&RCTUIManager.viewConfigs.RCTView||{}; for(var prop in viewConfig.nativeProps){ var viewAny=View; if(!viewAny.propTypes[prop]&&!ReactNativeStyleAttributes[prop]){ throw new Error( 'View is missing propType for native prop `'+prop+'`');}}} var ViewToExport=RCTView; if(__DEV__){ ViewToExport=View;} module.exports=ViewToExport; }); __d('ReactNativeViewAttributes',function(global, require, module, exports) { 'use strict'; var ReactNativeStyleAttributes=require('ReactNativeStyleAttributes'); var ReactNativeViewAttributes={}; ReactNativeViewAttributes.UIView={ pointerEvents:true, accessible:true, accessibilityLabel:true, accessibilityComponentType:true, accessibilityLiveRegion:true, accessibilityTraits:true, importantForAccessibility:true, testID:true, renderToHardwareTextureAndroid:true, shouldRasterizeIOS:true, onLayout:true, onAccessibilityTap:true, onMagicTap:true, collapsable:true, needsOffscreenAlphaCompositing:true, style:ReactNativeStyleAttributes}; ReactNativeViewAttributes.RCTView=babelHelpers.extends({}, ReactNativeViewAttributes.UIView,{ removeClippedSubviews:true}); module.exports=ReactNativeViewAttributes; }); __d('StyleSheetPropType',function(global, require, module, exports) { 'use strict'; var createStrictShapeTypeChecker=require('createStrictShapeTypeChecker'); var flattenStyle=require('flattenStyle'); function StyleSheetPropType( shape) { var shapePropType=createStrictShapeTypeChecker(shape); return function(props,propName,componentName,location){ var newProps=props; if(props[propName]){ newProps={}; newProps[propName]=flattenStyle(props[propName]);} return shapePropType(newProps,propName,componentName,location);};} module.exports=StyleSheetPropType; }); __d('createStrictShapeTypeChecker',function(global, require, module, exports) { 'use strict'; var ReactPropTypeLocationNames=require('ReactPropTypeLocationNames'); var invariant=require('invariant'); var merge=require('merge'); function createStrictShapeTypeChecker( shapeTypes) { function checkType(isRequired,props,propName,componentName,location){ if(!props[propName]){ if(isRequired){ invariant( false, 'Required object `'+propName+'` was not specified in '+('`'+ componentName+'`.'));} return;} var propValue=props[propName]; var propType=typeof propValue; var locationName= location&&ReactPropTypeLocationNames[location]||'(unknown)'; if(propType!=='object'){ invariant( false, 'Invalid '+locationName+' `'+propName+'` of type `'+propType+'` '+('supplied to `'+ componentName+'`, expected `object`.'));} var allKeys=merge(props[propName],shapeTypes); for(var key in allKeys){ var checker=shapeTypes[key]; if(!checker){ invariant( false, 'Invalid props.'+propName+' key `'+key+'` supplied to `'+componentName+'`.'+'\nBad object: '+ JSON.stringify(props[propName],null,' ')+'\nValid keys: '+ JSON.stringify(Object.keys(shapeTypes),null,' '));} var error=checker(propValue,key,componentName,location); if(error){ invariant( false, error.message+'\nBad object: '+ JSON.stringify(props[propName],null,' '));}}} function chainedCheckType( props, propName, componentName, location) { return checkType(false,props,propName,componentName,location);} chainedCheckType.isRequired=checkType.bind(null,true); return chainedCheckType;} module.exports=createStrictShapeTypeChecker; }); __d('requireNativeComponent',function(global, require, module, exports) { 'use strict'; var RCTUIManager=require('NativeModules').UIManager; var ReactNativeStyleAttributes=require('ReactNativeStyleAttributes'); var UnimplementedView=require('UnimplementedView'); var createReactNativeComponentClass=require('createReactNativeComponentClass'); var insetsDiffer=require('insetsDiffer'); var pointsDiffer=require('pointsDiffer'); var matricesDiffer=require('matricesDiffer'); var processColor=require('processColor'); var sizesDiffer=require('sizesDiffer'); var verifyPropTypes=require('verifyPropTypes'); var warning=require('warning'); function requireNativeComponent( viewName, componentInterface, extraConfig) { var viewConfig=RCTUIManager[viewName]; if(!viewConfig||!viewConfig.NativeProps){ warning(false,'Native component for "%s" does not exist',viewName); return UnimplementedView;} var nativeProps=babelHelpers.extends({}, RCTUIManager.RCTView.NativeProps, viewConfig.NativeProps); viewConfig.uiViewClassName=viewName; viewConfig.validAttributes={}; viewConfig.propTypes=componentInterface&&componentInterface.propTypes; for(var key in nativeProps){ var useAttribute=false; var attribute={}; var differ=TypeToDifferMap[nativeProps[key]]; if(differ){ attribute.diff=differ; useAttribute=true;} var processor=TypeToProcessorMap[nativeProps[key]]; if(processor){ attribute.process=processor; useAttribute=true;} viewConfig.validAttributes[key]=useAttribute?attribute:true;} viewConfig.validAttributes.style=ReactNativeStyleAttributes; if(__DEV__){ componentInterface&&verifyPropTypes( componentInterface, viewConfig, extraConfig&&extraConfig.nativeOnly);} return createReactNativeComponentClass(viewConfig);} var TypeToDifferMap={ CATransform3D:matricesDiffer, CGPoint:pointsDiffer, CGSize:sizesDiffer, UIEdgeInsets:insetsDiffer}; var TypeToProcessorMap={ CGColor:processColor, CGColorArray:processColor, UIColor:processColor, UIColorArray:processColor, Color:processColor}; module.exports=requireNativeComponent; }); __d('verifyPropTypes',function(global, require, module, exports) { 'use strict'; var ReactNativeStyleAttributes=require('ReactNativeStyleAttributes'); function verifyPropTypes( componentInterface, viewConfig, nativePropsToIgnore) { if(!viewConfig){ return;} var componentName=componentInterface.name|| componentInterface.displayName|| 'unknown'; if(!componentInterface.propTypes){ throw new Error( '`'+componentName+'` has no propTypes defined`');} var nativeProps=viewConfig.NativeProps; for(var prop in nativeProps){ if(!componentInterface.propTypes[prop]&& !ReactNativeStyleAttributes[prop]&&( !nativePropsToIgnore||!nativePropsToIgnore[prop])){ throw new Error( '`'+componentName+'` has no propType for native prop `'+ viewConfig.uiViewClassName+'.'+prop+'` of native type `'+ nativeProps[prop]+'`');}}} module.exports=verifyPropTypes; }); __d('UnimplementedView',function(global, require, module, exports) { 'use strict'; var React=require('React'); var StyleSheet=require('StyleSheet'); var View=require('View'); var UnimplementedView=React.createClass({displayName:'UnimplementedView', setNativeProps:function(){}, render:function(){ return ( React.createElement(View,{style:[styles.unimplementedView,this.props.style]}, this.props.children));}}); var styles=StyleSheet.create({ unimplementedView:{ borderWidth:1, borderColor:'red', alignSelf:'flex-start'}}); module.exports=UnimplementedView; }); __d('insetsDiffer',function(global, require, module, exports) { 'use strict'; var dummyInsets={ top:undefined, left:undefined, right:undefined, bottom:undefined}; var insetsDiffer=function( one, two) { one=one||dummyInsets; two=two||dummyInsets; return one!==two&&( one.top!==two.top|| one.left!==two.left|| one.right!==two.right|| one.bottom!==two.bottom);}; module.exports=insetsDiffer; }); __d('pointsDiffer',function(global, require, module, exports) { 'use strict'; var dummyPoint={x:undefined,y:undefined}; var pointsDiffer=function(one,two){ one=one||dummyPoint; two=two||dummyPoint; return one!==two&&( one.x!==two.x|| one.y!==two.y);}; module.exports=pointsDiffer; }); __d('ReactNativeART',function(global, require, module, exports) { 'use strict'; var Color=require('art/core/color.js'); var Path=require('ARTSerializablePath'); var Transform=require('art/core/transform.js'); var React=require('React'); var ReactNativeViewAttributes=require('ReactNativeViewAttributes'); var createReactNativeComponentClass=require('createReactNativeComponentClass'); var merge=require('merge'); function arrayDiffer(a,b){ if(a==null){ return true;} if(a.length!==b.length){ return true;} for(var i=0;ig){ cx-=gx; cy-=gy;}else if(u>0&&g!=0){ cx-=u/g*gx; cy-=u/g*gy;} v1=cx*cx+cy*cy; cx=c2x-sx;cy=c2y-sy; u=cx*gx+cy*gy; if(u>g){ cx-=gx; cy-=gy;}else if(u>0&&g!=0){ cx-=u/g*gx; cy-=u/g*gy;} v2=cx*cx+cy*cy; if(v1<0.01&&v2<0.01){ this.onLine(sx,sy,ex,ey); return;} if(isNaN(v1)||isNaN(v2)){ throw new Error('Bad input');} var s1x=(c1x+c2x)*0.5,s1y=(c1y+c2y)*0.5, l1x=(c1x+sx)*0.5,l1y=(c1y+sy)*0.5, l2x=(l1x+s1x)*0.5,l2y=(l1y+s1y)*0.5, r2x=(ex+c2x)*0.5,r2y=(ey+c2y)*0.5, r1x=(r2x+s1x)*0.5,r1y=(r2y+s1y)*0.5, l2r1x=(l2x+r1x)*0.5,l2r1y=(l2y+r1y)*0.5; this.onBezierCurve(sx,sy,l1x,l1y,l2x,l2y,l2r1x,l2r1y); this.onBezierCurve(l2r1x,l2r1y,r1x,r1y,r2x,r2y,ex,ey);}, onArc:function(sx,sy,ex,ey,cx,cy,rx,ry,sa,ea,ccw,rotation){ var rad=rotation?rotation*Math.PI/180:0,cos=Math.cos(rad),sin=Math.sin(rad), xx=cos*rx,yx=-sin*ry, xy=sin*rx,yy=cos*ry; var arc=ea-sa; if(arc<0&&!ccw)arc+=Math.PI*2;else if(arc>0&&ccw)arc-=Math.PI*2; var n=Math.ceil(Math.abs(arc/(Math.PI/2))), step=arc/n, k=4/3*Math.tan(step/4); var x=Math.cos(sa),y=Math.sin(sa); for(var i=0;im.yy/m.xy?-1:1; if(m.xx<0?m.xy>=0:m.xy<0)flip=-flip; return this.rotate(deg-Math.atan2(flip*m.yx,flip*m.xx)*180/Math.PI,x,y);}, scaleTo:function(x,y){ var m=this; var h=Math.sqrt(m.xx*m.xx+m.yx*m.yx); m.xx/=h;m.yx/=h; h=Math.sqrt(m.yy*m.yy+m.xy*m.xy); m.yy/=h;m.xy/=h; return this.scale(x,y);}, resizeTo:function(width,height){ var w=this.width,h=this.height; if(!w||!h)return this; return this.scaleTo(width/w,height/h);}, inversePoint:function(x,y){ var a=this.xx,b=this.yx, c=this.xy,d=this.yy, e=this.x,f=this.y; var det=b*c-a*d; if(det==0)return null; return { x:(d*(e-x)+c*(y-f))/det, y:(a*(f-y)+b*(x-e))/det};}, point:function(x,y){ var m=this; return { x:m.xx*x+m.xy*y+m.x, y:m.yx*x+m.yy*y+m.y};}}); }); __d('DatePickerIOS',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var PropTypes=require('ReactPropTypes'); var React=require('React'); var RCTDatePickerIOSConsts=require('NativeModules').UIManager.RCTDatePicker.Constants; var StyleSheet=require('StyleSheet'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var DATEPICKER='datepicker'; var DatePickerIOS=React.createClass({displayName:'DatePickerIOS', mixins:[NativeMethodsMixin], propTypes:babelHelpers.extends({}, View.propTypes,{ date:PropTypes.instanceOf(Date).isRequired, onDateChange:PropTypes.func.isRequired, maximumDate:PropTypes.instanceOf(Date), minimumDate:PropTypes.instanceOf(Date), mode:PropTypes.oneOf(['date','time','datetime']), minuteInterval:PropTypes.oneOf([1,2,3,4,5,6,10,12,15,20,30]), timeZoneOffsetInMinutes:PropTypes.number}), getDefaultProps:function(){ return { mode:'datetime'};}, _onChange:function(event){ var nativeTimeStamp=event.nativeEvent.timestamp; this.props.onDateChange&&this.props.onDateChange( new Date(nativeTimeStamp)); this.props.onChange&&this.props.onChange(event); var propsTimeStamp=this.props.date.getTime(); if(nativeTimeStamp!==propsTimeStamp){ this.refs[DATEPICKER].setNativeProps({ date:propsTimeStamp});}}, render:function(){ var props=this.props; return ( React.createElement(View,{style:props.style}, React.createElement(RCTDatePickerIOS,{ ref:DATEPICKER, style:styles.datePickerIOS, date:props.date.getTime(), maximumDate: props.maximumDate?props.maximumDate.getTime():undefined, minimumDate: props.minimumDate?props.minimumDate.getTime():undefined, mode:props.mode, minuteInterval:props.minuteInterval, timeZoneOffsetInMinutes:props.timeZoneOffsetInMinutes, onChange:this._onChange})));}}); var styles=StyleSheet.create({ datePickerIOS:{ height:RCTDatePickerIOSConsts.ComponentHeight, width:RCTDatePickerIOSConsts.ComponentWidth}}); var RCTDatePickerIOS=requireNativeComponent('RCTDatePicker',DatePickerIOS,{ nativeOnly:{onChange:true}}); module.exports=DatePickerIOS; }); __d('DrawerLayoutAndroid',function(global, require, module, exports) { 'use strict'; module.exports=require('UnimplementedView'); }); __d('Image',function(global, require, module, exports) { 'use strict'; var EdgeInsetsPropType=require('EdgeInsetsPropType'); var ImageResizeMode=require('ImageResizeMode'); var ImageStylePropTypes=require('ImageStylePropTypes'); var NativeMethodsMixin=require('NativeMethodsMixin'); var NativeModules=require('NativeModules'); var PropTypes=require('ReactPropTypes'); var React=require('React'); var ReactNativeViewAttributes=require('ReactNativeViewAttributes'); var View=require('View'); var StyleSheet=require('StyleSheet'); var StyleSheetPropType=require('StyleSheetPropType'); var flattenStyle=require('flattenStyle'); var invariant=require('invariant'); var requireNativeComponent=require('requireNativeComponent'); var resolveAssetSource=require('resolveAssetSource'); var warning=require('warning'); var Image=React.createClass({displayName:'Image', propTypes:{ style:StyleSheetPropType(ImageStylePropTypes), source:PropTypes.oneOfType([ PropTypes.shape({ uri:PropTypes.string}), PropTypes.number]), defaultSource:PropTypes.shape({ uri:PropTypes.string}), accessible:PropTypes.bool, accessibilityLabel:PropTypes.string, capInsets:EdgeInsetsPropType, resizeMode:PropTypes.oneOf(['cover','contain','stretch']), testID:PropTypes.string, onLayout:PropTypes.func, onLoadStart:PropTypes.func, onProgress:PropTypes.func, onError:PropTypes.func, onLoad:PropTypes.func, onLoadEnd:PropTypes.func}, statics:{ resizeMode:ImageResizeMode}, mixins:[NativeMethodsMixin], viewConfig:{ uiViewClassName:'UIView', validAttributes:ReactNativeViewAttributes.UIView}, contextTypes:{ isInAParentText:React.PropTypes.bool}, render:function(){ for(var prop in cfg.nativeOnly){ if(this.props[prop]!==undefined){ console.warn('Prop `'+prop+' = '+this.props[prop]+'` should '+ 'not be set directly on Image.');}} var source=resolveAssetSource(this.props.source)||{}; var defaultSource=this.props.defaultSource&&resolveAssetSource(this.props.defaultSource)||{};var width=source.width;var height=source.height; var style=flattenStyle([{width:width,height:height},styles.base,this.props.style])||{}; if(source.uri===''){ console.warn('source.uri should not be an empty string'); return React.createElement(View,babelHelpers.extends({},this.props,{style:style}));} var isNetwork=source.uri&&source.uri.match(/^https?:/); var RawImage=isNetwork?RCTNetworkImageView:RCTImageView; var resizeMode=this.props.resizeMode||(style||{}).resizeMode||'cover'; var tintColor=(style||{}).tintColor; if(isNetwork&&tintColor){ RawImage=RCTImageView;} if(this.context.isInAParentText){ return React.createElement(RCTVirtualImage,{source:source});}else { return ( React.createElement(RawImage,babelHelpers.extends({}, this.props,{ style:style, resizeMode:resizeMode, tintColor:tintColor, src:source.uri, defaultImageSrc:defaultSource.uri})));}}}); var styles=StyleSheet.create({ base:{ overflow:'hidden'}}); var cfg={ nativeOnly:{ src:true, defaultImageSrc:true, imageTag:true, progressHandlerRegistered:true}}; var RCTImageView=requireNativeComponent('RCTImageView',Image,cfg); var RCTNetworkImageView=NativeModules.NetworkImageViewManager?requireNativeComponent('RCTNetworkImageView',Image,cfg):RCTImageView; var RCTVirtualImage=requireNativeComponent('RCTVirtualImage',Image); module.exports=Image; }); __d('EdgeInsetsPropType',function(global, require, module, exports) { 'use strict'; var PropTypes=require('ReactPropTypes'); var createStrictShapeTypeChecker=require('createStrictShapeTypeChecker'); var EdgeInsetsPropType=createStrictShapeTypeChecker({ top:PropTypes.number, left:PropTypes.number, bottom:PropTypes.number, right:PropTypes.number}); module.exports=EdgeInsetsPropType; }); __d('resolveAssetSource',function(global, require, module, exports) { 'use strict'; var AssetRegistry=require('AssetRegistry'); var PixelRatio=require('PixelRatio'); var Platform=require('Platform'); var SourceCode=require('NativeModules').SourceCode; var _serverURL,_offlinePath; function getDevServerURL(){ if(_serverURL===undefined){ var scriptURL=SourceCode.scriptURL; var match=scriptURL&&scriptURL.match(/^https?:\/\/.*?\//); if(match){ _serverURL=match[0];}else { _serverURL=null;}} return _serverURL;} function getOfflinePath(){ if(_offlinePath===undefined){ var scriptURL=SourceCode.scriptURL; var match=scriptURL&&scriptURL.match(/^file:\/\/(\/.*\/)/); if(match){ _offlinePath=match[1];}else { _offlinePath='';}} return _offlinePath;} function getPathInArchive(asset){ if(Platform.OS==='android'){ var assetDir=getBasePath(asset); return (assetDir+'/'+asset.name). toLowerCase(). replace(/\//g,'_'). replace(/([^a-z0-9_])/g,''). replace(/^assets_/,'');}else { return getOfflinePath()+getScaledAssetPath(asset);}} function getPathOnDevserver(devServerUrl,asset){ return devServerUrl+getScaledAssetPath(asset)+'?platform='+Platform.OS+ '&hash='+asset.hash;} function getBasePath(asset){ var path=asset.httpServerLocation; if(path[0]==='/'){ path=path.substr(1);} return path;} function getScaledAssetPath(asset){ var scale=pickScale(asset.scales,PixelRatio.get()); var scaleSuffix=scale===1?'':'@'+scale+'x'; var assetDir=getBasePath(asset); return assetDir+'/'+asset.name+scaleSuffix+'.'+asset.type;} function pickScale(scales,deviceScale){ for(var i=0;i=deviceScale){ return scales[i];}} return scales[scales.length-1]||1;} function resolveAssetSource(source){ if(typeof source==='object'){ return source;} var asset=AssetRegistry.getAssetByID(source); if(asset){ return assetToImageSource(asset);} return null;} function assetToImageSource(asset){ var devServerURL=getDevServerURL(); return { __packager_asset:true, width:asset.width, height:asset.height, uri:devServerURL?getPathOnDevserver(devServerURL,asset):getPathInArchive(asset), scale:pickScale(asset.scales,PixelRatio.get())};} module.exports=resolveAssetSource; module.exports.pickScale=pickScale; }); __d('AssetRegistry',function(global, require, module, exports) { 'use strict'; var assets=[]; function registerAsset(asset){ return assets.push(asset);} function getAssetByID(assetId){ return assets[assetId-1];} module.exports={registerAsset:registerAsset,getAssetByID:getAssetByID}; }); __d('PixelRatio',function(global, require, module, exports) { 'use strict'; var Dimensions=require('Dimensions');var PixelRatio=(function(){function PixelRatio(){babelHelpers.classCallCheck(this,PixelRatio);}babelHelpers.createClass(PixelRatio,null,[{key:'get',value:function get() { return Dimensions.get('window').scale;}},{key:'getFontScale',value:function getFontScale() { return Dimensions.get('window').fontScale||PixelRatio.get();}},{key:'getPixelSizeForLayoutSize',value:function getPixelSizeForLayoutSize( layoutSize){ return Math.round(layoutSize*PixelRatio.get());}},{key:'startDetecting',value:function startDetecting() {}}]);return PixelRatio;})(); module.exports=PixelRatio; }); __d('Dimensions',function(global, require, module, exports) { 'use strict'; var NativeModules=require('NativeModules'); var invariant=require('invariant'); var dimensions=NativeModules.UIManager.Dimensions; if(dimensions&&dimensions.windowPhysicalPixels){ dimensions=JSON.parse(JSON.stringify(dimensions)); var windowPhysicalPixels=dimensions.windowPhysicalPixels; dimensions.window={ width:windowPhysicalPixels.width/windowPhysicalPixels.scale, height:windowPhysicalPixels.height/windowPhysicalPixels.scale, scale:windowPhysicalPixels.scale, fontScale:windowPhysicalPixels.fontScale}; delete dimensions.windowPhysicalPixels;}var Dimensions=(function(){function Dimensions(){babelHelpers.classCallCheck(this,Dimensions);}babelHelpers.createClass(Dimensions,null,[{key:'set',value:function set( dims){ babelHelpers.extends(dimensions,dims); return true;}},{key:'get',value:function get( dim){ invariant(dimensions[dim],'No dimension set for key '+dim); return dimensions[dim];}}]);return Dimensions;})(); module.exports=Dimensions; }); __d('ListView',function(global, require, module, exports) { 'use strict'; var ListViewDataSource=require('ListViewDataSource'); var React=require('React'); var RCTUIManager=require('NativeModules').UIManager; var RCTScrollViewManager=require('NativeModules').ScrollViewManager; var ScrollView=require('ScrollView'); var ScrollResponder=require('ScrollResponder'); var StaticRenderer=require('StaticRenderer'); var TimerMixin=require('react-timer-mixin/TimerMixin.js'); var isEmpty=require('isEmpty'); var logError=require('logError'); var merge=require('merge'); var PropTypes=React.PropTypes; var DEFAULT_PAGE_SIZE=1; var DEFAULT_INITIAL_ROWS=10; var DEFAULT_SCROLL_RENDER_AHEAD=1000; var DEFAULT_END_REACHED_THRESHOLD=1000; var DEFAULT_SCROLL_CALLBACK_THROTTLE=50; var SCROLLVIEW_REF='listviewscroll'; var ListView=React.createClass({displayName:'ListView', mixins:[ScrollResponder.Mixin,TimerMixin], statics:{ DataSource:ListViewDataSource}, propTypes:babelHelpers.extends({}, ScrollView.propTypes,{ dataSource:PropTypes.instanceOf(ListViewDataSource).isRequired, renderSeparator:PropTypes.func, renderRow:PropTypes.func.isRequired, initialListSize:PropTypes.number, onEndReached:PropTypes.func, onEndReachedThreshold:PropTypes.number, pageSize:PropTypes.number, renderFooter:PropTypes.func, renderHeader:PropTypes.func, renderSectionHeader:PropTypes.func, renderScrollComponent:React.PropTypes.func.isRequired, scrollRenderAheadDistance:React.PropTypes.number, onChangeVisibleRows:React.PropTypes.func, removeClippedSubviews:React.PropTypes.bool}), getMetrics:function(){ return { contentLength:this.scrollProperties.contentLength, totalRows:this.props.dataSource.getRowCount(), renderedRows:this.state.curRenderedRowsCount, visibleRows:Object.keys(this._visibleRows).length};}, getScrollResponder:function(){ return this.refs[SCROLLVIEW_REF]&& this.refs[SCROLLVIEW_REF].getScrollResponder&& this.refs[SCROLLVIEW_REF].getScrollResponder();}, setNativeProps:function(props){ this.refs[SCROLLVIEW_REF].setNativeProps(props);}, getDefaultProps:function(){ return { initialListSize:DEFAULT_INITIAL_ROWS, pageSize:DEFAULT_PAGE_SIZE, renderScrollComponent:function(props){return React.createElement(ScrollView,props);}, scrollRenderAheadDistance:DEFAULT_SCROLL_RENDER_AHEAD, onEndReachedThreshold:DEFAULT_END_REACHED_THRESHOLD};}, getInitialState:function(){ return { curRenderedRowsCount:this.props.initialListSize, prevRenderedRowsCount:0, highlightedRow:{}};}, getInnerViewNode:function(){ return this.refs[SCROLLVIEW_REF].getInnerViewNode();}, componentWillMount:function(){ this.scrollProperties={ visibleLength:null, contentLength:null, offset:0}; this._childFrames=[]; this._visibleRows={};}, componentDidMount:function(){var _this=this; this.requestAnimationFrame(function(){ _this._measureAndUpdateScrollProps();});}, componentWillReceiveProps:function(nextProps){ if(this.props.dataSource!==nextProps.dataSource){ this.setState(function(state,props){ var rowsToRender=Math.min( state.curRenderedRowsCount+props.pageSize, props.dataSource.getRowCount()); return { prevRenderedRowsCount:0, curRenderedRowsCount:rowsToRender};});}}, componentDidUpdate:function(){var _this2=this; this.requestAnimationFrame(function(){ _this2._measureAndUpdateScrollProps();});}, onRowHighlighted:function(sectionID,rowID){ this.setState({highlightedRow:{sectionID:sectionID,rowID:rowID}});}, render:function(){ var bodyComponents=[]; var dataSource=this.props.dataSource; var allRowIDs=dataSource.rowIdentities; var rowCount=0; var sectionHeaderIndices=[]; var header=this.props.renderHeader&&this.props.renderHeader(); var footer=this.props.renderFooter&&this.props.renderFooter(); var totalIndex=header?1:0; for(var sectionIdx=0;sectionIdx=this.state.prevRenderedRowsCount&& dataSource.sectionHeaderShouldUpdate(sectionIdx); bodyComponents.push( React.createElement(StaticRenderer,{ key:'s_'+sectionID, shouldUpdate:!!shouldUpdateHeader, render:this.props.renderSectionHeader.bind( null, dataSource.getSectionHeaderData(sectionIdx), sectionID)})); sectionHeaderIndices.push(totalIndex++);} for(var rowIdx=0;rowIdx=this.state.prevRenderedRowsCount&& dataSource.rowShouldUpdate(sectionIdx,rowIdx); var row= React.createElement(StaticRenderer,{ key:'r_'+comboID, shouldUpdate:!!shouldUpdateRow, render:this.props.renderRow.bind( null, dataSource.getRowData(sectionIdx,rowIdx), sectionID, rowID, this.onRowHighlighted)}); bodyComponents.push(row); totalIndex++; if(this.props.renderSeparator&&( rowIdx!==rowIDs.length-1||sectionIdx===allRowIDs.length-1)){ var adjacentRowHighlighted= this.state.highlightedRow.sectionID===sectionID&&( this.state.highlightedRow.rowID===rowID|| this.state.highlightedRow.rowID===rowIDs[rowIdx+1]); var separator=this.props.renderSeparator( sectionID, rowID, adjacentRowHighlighted); bodyComponents.push(separator); totalIndex++;} if(++rowCount===this.state.curRenderedRowsCount){ break;}} if(rowCount>=this.state.curRenderedRowsCount){ break;}}var _props= this.props;var renderScrollComponent=_props.renderScrollComponent;var props=babelHelpers.objectWithoutProperties(_props,['renderScrollComponent']); if(!props.scrollEventThrottle){ props.scrollEventThrottle=DEFAULT_SCROLL_CALLBACK_THROTTLE;} if(props.removeClippedSubviews===undefined){ props.removeClippedSubviews=true;} babelHelpers.extends(props,{ onScroll:this._onScroll, stickyHeaderIndices:sectionHeaderIndices, onKeyboardWillShow:undefined, onKeyboardWillHide:undefined, onKeyboardDidShow:undefined, onKeyboardDidHide:undefined}); return React.cloneElement(renderScrollComponent(props),{ ref:SCROLLVIEW_REF, onContentSizeChange:this._onContentSizeChange, onLayout:this._onLayout}, header,bodyComponents,footer);}, _measureAndUpdateScrollProps:function(){ var scrollComponent=this.getScrollResponder(); if(!scrollComponent||!scrollComponent.getInnerViewNode){ return;} RCTScrollViewManager&&RCTScrollViewManager.calculateChildFrames&& RCTScrollViewManager.calculateChildFrames( React.findNodeHandle(scrollComponent), this._updateChildFrames);}, _onContentSizeChange:function(width,height){ this.scrollProperties.contentLength=!this.props.horizontal? height:width; this._updateVisibleRows(); this._renderMoreRowsIfNeeded();}, _onLayout:function(event){var _event$nativeEvent$la= event.nativeEvent.layout;var width=_event$nativeEvent$la.width;var height=_event$nativeEvent$la.height; this.scrollProperties.visibleLength=!this.props.horizontal? height:width; this._updateVisibleRows(); this._renderMoreRowsIfNeeded();}, _setScrollVisibleLength:function(left,top,width,height){ this.scrollProperties.visibleLength=!this.props.horizontal? height:width; this._updateVisibleRows(); this._renderMoreRowsIfNeeded();}, _updateChildFrames:function(childFrames){ this._updateVisibleRows(childFrames);}, _maybeCallOnEndReached:function(event){ if(this.props.onEndReached&& this.scrollProperties.contentLength!==this._sentEndForContentLength&& this._getDistanceFromEnd(this.scrollProperties)visibleMax||maxthis.props.onEndReachedThreshold){ this._sentEndForContentLength=null;} this.props.onScroll&&this.props.onScroll(e);}}); module.exports=ListView; }); __d('ListViewDataSource',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var isEmpty=require('isEmpty'); var warning=require('warning'); function defaultGetRowData( dataBlob, sectionID, rowID) { return dataBlob[sectionID][rowID];} function defaultGetSectionHeaderData( dataBlob, sectionID) { return dataBlob[sectionID];}var ListViewDataSource=(function(){ function ListViewDataSource(params){babelHelpers.classCallCheck(this,ListViewDataSource); invariant( params&&typeof params.rowHasChanged==='function', 'Must provide a rowHasChanged function.'); this._rowHasChanged=params.rowHasChanged; this._getRowData=params.getRowData||defaultGetRowData; this._sectionHeaderHasChanged=params.sectionHeaderHasChanged; this._getSectionHeaderData= params.getSectionHeaderData||defaultGetSectionHeaderData; this._dataBlob=null; this._dirtyRows=[]; this._dirtySections=[]; this._cachedRowCount=0; this.rowIdentities=[]; this.sectionIdentities=[];}babelHelpers.createClass(ListViewDataSource,[{key:'cloneWithRows',value:function cloneWithRows( dataBlob, rowIdentities) { var rowIds=rowIdentities?[rowIdentities]:null; if(!this._sectionHeaderHasChanged){ this._sectionHeaderHasChanged=function(){return false;};} return this.cloneWithRowsAndSections({s1:dataBlob},['s1'],rowIds);}},{key:'cloneWithRowsAndSections',value:function cloneWithRowsAndSections( dataBlob, sectionIdentities, rowIdentities) { invariant( typeof this._sectionHeaderHasChanged==='function', 'Must provide a sectionHeaderHasChanged function with section data.'); var newSource=new ListViewDataSource({ getRowData:this._getRowData, getSectionHeaderData:this._getSectionHeaderData, rowHasChanged:this._rowHasChanged, sectionHeaderHasChanged:this._sectionHeaderHasChanged}); newSource._dataBlob=dataBlob; if(sectionIdentities){ newSource.sectionIdentities=sectionIdentities;}else { newSource.sectionIdentities=Object.keys(dataBlob);} if(rowIdentities){ newSource.rowIdentities=rowIdentities;}else { newSource.rowIdentities=[]; newSource.sectionIdentities.forEach(function(sectionID){ newSource.rowIdentities.push(Object.keys(dataBlob[sectionID]));});} newSource._cachedRowCount=countRows(newSource.rowIdentities); newSource._calculateDirtyArrays( this._dataBlob, this.sectionIdentities, this.rowIdentities); return newSource;}},{key:'getRowCount',value:function getRowCount() { return this._cachedRowCount;}},{key:'rowShouldUpdate',value:function rowShouldUpdate( sectionIndex,rowIndex){ var needsUpdate=this._dirtyRows[sectionIndex][rowIndex]; warning(needsUpdate!==undefined, 'missing dirtyBit for section, row: '+sectionIndex+', '+rowIndex); return needsUpdate;}},{key:'getRowData',value:function getRowData( sectionIndex,rowIndex){ var sectionID=this.sectionIdentities[sectionIndex]; var rowID=this.rowIdentities[sectionIndex][rowIndex]; warning( sectionID!==undefined&&rowID!==undefined, 'rendering invalid section, row: '+sectionIndex+', '+rowIndex); return this._getRowData(this._dataBlob,sectionID,rowID);}},{key:'getRowIDForFlatIndex',value:function getRowIDForFlatIndex( index){ var accessIndex=index; for(var ii=0;ii=this.rowIdentities[ii].length){ accessIndex-=this.rowIdentities[ii].length;}else { return this.rowIdentities[ii][accessIndex];}} return null;}},{key:'getSectionIDForFlatIndex',value:function getSectionIDForFlatIndex( index){ var accessIndex=index; for(var ii=0;ii=this.rowIdentities[ii].length){ accessIndex-=this.rowIdentities[ii].length;}else { return this.sectionIdentities[ii];}} return null;}},{key:'getSectionLengths',value:function getSectionLengths() { var results=[]; for(var ii=0;ii but not '+ '`scrollEventThrottle`. You will only receive one event. '+ 'Using `16` you get all the events but be aware that it may '+ 'cause frame drops, use a bigger number if you don\'t need as '+ 'much precision.');}} if(Platform.OS==='android'){ if(this.props.keyboardDismissMode==='on-drag'){ dismissKeyboard();}} this.scrollResponderHandleScroll(e);}, _handleContentOnLayout:function(e){var _e$nativeEvent$layout= e.nativeEvent.layout;var width=_e$nativeEvent$layout.width;var height=_e$nativeEvent$layout.height; this.props.onContentSizeChange&&this.props.onContentSizeChange(width,height);}, render:function(){ var contentContainerStyle=[ this.props.horizontal&&styles.contentContainerHorizontal, this.props.contentContainerStyle]; if(__DEV__&&this.props.style){ var style=flattenStyle(this.props.style); var childLayoutProps=['alignItems','justifyContent']. filter(function(prop){return style&&style[prop]!==undefined;}); invariant( childLayoutProps.length===0, 'ScrollView child layout ('+JSON.stringify(childLayoutProps)+ ') must by applied through the contentContainerStyle prop.');} var contentSizeChangeProps={}; if(this.props.onContentSizeChange){ contentSizeChangeProps={ onLayout:this._handleContentOnLayout};} var contentContainer= React.createElement(View,babelHelpers.extends({}, contentSizeChangeProps,{ ref:INNERVIEW, style:contentContainerStyle, removeClippedSubviews:this.props.removeClippedSubviews, collapsable:false}), this.props.children); var alwaysBounceHorizontal= this.props.alwaysBounceHorizontal!==undefined? this.props.alwaysBounceHorizontal: this.props.horizontal; var alwaysBounceVertical= this.props.alwaysBounceVertical!==undefined? this.props.alwaysBounceVertical: !this.props.horizontal; var props=babelHelpers.extends({}, this.props,{ alwaysBounceHorizontal:alwaysBounceHorizontal, alwaysBounceVertical:alwaysBounceVertical, style:[styles.base,this.props.style], onTouchStart:this.scrollResponderHandleTouchStart, onTouchMove:this.scrollResponderHandleTouchMove, onTouchEnd:this.scrollResponderHandleTouchEnd, onScrollBeginDrag:this.scrollResponderHandleScrollBeginDrag, onScrollEndDrag:this.scrollResponderHandleScrollEndDrag, onMomentumScrollBegin:this.scrollResponderHandleMomentumScrollBegin, onMomentumScrollEnd:this.scrollResponderHandleMomentumScrollEnd, onStartShouldSetResponder:this.scrollResponderHandleStartShouldSetResponder, onStartShouldSetResponderCapture:this.scrollResponderHandleStartShouldSetResponderCapture, onScrollShouldSetResponder:this.scrollResponderHandleScrollShouldSetResponder, onScroll:this.handleScroll, onResponderGrant:this.scrollResponderHandleResponderGrant, onResponderTerminationRequest:this.scrollResponderHandleTerminationRequest, onResponderTerminate:this.scrollResponderHandleTerminate, onResponderRelease:this.scrollResponderHandleResponderRelease, onResponderReject:this.scrollResponderHandleResponderReject}); var onRefreshStart=this.props.onRefreshStart; props.onRefreshStart=onRefreshStart? (function(){onRefreshStart&&onRefreshStart(this.endRefreshing);}).bind(this): null; var ScrollViewClass; if(Platform.OS==='ios'){ ScrollViewClass=RCTScrollView;}else if(Platform.OS==='android'){ if(this.props.horizontal){ ScrollViewClass=AndroidHorizontalScrollView;}else { ScrollViewClass=AndroidScrollView;}} invariant( ScrollViewClass!==undefined, 'ScrollViewClass must not be undefined'); return ( React.createElement(ScrollViewClass,babelHelpers.extends({},props,{ref:SCROLLVIEW}), contentContainer));}}); var styles=StyleSheet.create({ base:{ flex:1}, contentContainerHorizontal:{ alignSelf:'flex-start', flexDirection:'row'}}); var validAttributes=babelHelpers.extends({}, ReactNativeViewAttributes.UIView,{ alwaysBounceHorizontal:true, alwaysBounceVertical:true, automaticallyAdjustContentInsets:true, bounces:true, centerContent:true, contentInset:{diff:insetsDiffer}, contentOffset:{diff:pointsDiffer}, decelerationRate:true, horizontal:true, keyboardDismissMode:true, keyboardShouldPersistTaps:true, maximumZoomScale:true, minimumZoomScale:true, pagingEnabled:true, removeClippedSubviews:true, scrollEnabled:true, scrollIndicatorInsets:{diff:insetsDiffer}, scrollsToTop:true, showsHorizontalScrollIndicator:true, showsVerticalScrollIndicator:true, snapToInterval:true, snapToAlignment:true, stickyHeaderIndices:{diff:deepDiffer}, scrollEventThrottle:true, zoomScale:true}); if(Platform.OS==='android'){ var AndroidScrollView=requireNativeComponent('RCTScrollView',ScrollView); var AndroidHorizontalScrollView=requireNativeComponent( 'AndroidHorizontalScrollView', ScrollView);}else if(Platform.OS==='ios'){ var RCTScrollView=requireNativeComponent('RCTScrollView',ScrollView);} module.exports=ScrollView; }); __d('PointPropType',function(global, require, module, exports) { 'use strict'; var PropTypes=require('ReactPropTypes'); var createStrictShapeTypeChecker=require('createStrictShapeTypeChecker'); var PointPropType=createStrictShapeTypeChecker({ x:PropTypes.number, y:PropTypes.number}); module.exports=PointPropType; }); __d('ScrollResponder',function(global, require, module, exports) { 'use strict'; var Dimensions=require('Dimensions'); var NativeModules=require('NativeModules'); var Platform=require('Platform'); var RCTDeviceEventEmitter=require('RCTDeviceEventEmitter'); var React=require('React'); var Subscribable=require('Subscribable'); var TextInputState=require('TextInputState'); var RCTUIManager=NativeModules.UIManager; var RCTScrollViewConsts=RCTUIManager.RCTScrollView.Constants; var warning=require('warning'); var IS_ANIMATING_TOUCH_START_THRESHOLD_MS=16; var ScrollResponderMixin={ mixins:[Subscribable.Mixin], statics:RCTScrollViewConsts, scrollResponderMixinGetInitialState:function(){ return { isTouching:false, lastMomentumScrollBeginTime:0, lastMomentumScrollEndTime:0, observedScrollSinceBecomingResponder:false, becameResponderWhileAnimating:false};}, scrollResponderHandleScrollShouldSetResponder:function(){ return this.state.isTouching;}, scrollResponderHandleStartShouldSetResponder:function(){ return false;}, scrollResponderHandleStartShouldSetResponderCapture:function(e){ var currentlyFocusedTextInput=TextInputState.currentlyFocusedField(); if(!this.props.keyboardShouldPersistTaps&& currentlyFocusedTextInput!=null&& e.target!==currentlyFocusedTextInput){ return true;} return this.scrollResponderIsAnimating();}, scrollResponderHandleResponderReject:function(){ warning(false,"ScrollView doesn't take rejection well - scrolls anyway");}, scrollResponderHandleTerminationRequest:function(){ return !this.state.observedScrollSinceBecomingResponder;}, scrollResponderHandleTouchEnd:function(e){ var nativeEvent=e.nativeEvent; this.state.isTouching=nativeEvent.touches.length!==0; this.props.onTouchEnd&&this.props.onTouchEnd(e);}, scrollResponderHandleResponderRelease:function(e){ this.props.onResponderRelease&&this.props.onResponderRelease(e); var currentlyFocusedTextInput=TextInputState.currentlyFocusedField(); if(!this.props.keyboardShouldPersistTaps&& currentlyFocusedTextInput!=null&& e.target!==currentlyFocusedTextInput&& !this.state.observedScrollSinceBecomingResponder&& !this.state.becameResponderWhileAnimating){ this.props.onScrollResponderKeyboardDismissed&& this.props.onScrollResponderKeyboardDismissed(e); TextInputState.blurTextInput(currentlyFocusedTextInput);}}, scrollResponderHandleScroll:function(e){ this.state.observedScrollSinceBecomingResponder=true; this.props.onScroll&&this.props.onScroll(e);}, scrollResponderHandleResponderGrant:function(e){ this.state.observedScrollSinceBecomingResponder=false; this.props.onResponderGrant&&this.props.onResponderGrant(e); this.state.becameResponderWhileAnimating=this.scrollResponderIsAnimating();}, scrollResponderHandleScrollBeginDrag:function(e){ this.props.onScrollBeginDrag&&this.props.onScrollBeginDrag(e);}, scrollResponderHandleScrollEndDrag:function(e){ this.props.onScrollEndDrag&&this.props.onScrollEndDrag(e);}, scrollResponderHandleMomentumScrollBegin:function(e){ this.state.lastMomentumScrollBeginTime=Date.now(); this.props.onMomentumScrollBegin&&this.props.onMomentumScrollBegin(e);}, scrollResponderHandleMomentumScrollEnd:function(e){ this.state.lastMomentumScrollEndTime=Date.now(); this.props.onMomentumScrollEnd&&this.props.onMomentumScrollEnd(e);}, scrollResponderHandleTouchStart:function(e){ this.state.isTouching=true; this.props.onTouchStart&&this.props.onTouchStart(e);}, scrollResponderHandleTouchMove:function(e){ this.props.onTouchMove&&this.props.onTouchMove(e);}, scrollResponderIsAnimating:function(){ var now=Date.now(); var timeSinceLastMomentumScrollEnd=now-this.state.lastMomentumScrollEndTime; var isAnimating=timeSinceLastMomentumScrollEnd=1, 'Navigator requires props.initialRoute or props.initialRouteStack.'); var initialRouteIndex=routeStack.length-1; if(this.props.initialRoute){ initialRouteIndex=routeStack.indexOf(this.props.initialRoute); invariant( initialRouteIndex!==-1, 'initialRoute is not in initialRouteStack.');} return { sceneConfigStack:routeStack.map( function(route){return _this.props.configureScene(route);}), routeStack:routeStack, presentedIndex:initialRouteIndex, transitionFromIndex:null, activeGesture:null, pendingGestureProgress:null, transitionQueue:[]};}, componentWillMount:function(){var _this2=this; this.__defineGetter__('navigationContext',this._getNavigationContext); this._subRouteFocus=[]; this.parentNavigator=this.props.navigator; this._handlers={}; this.springSystem=new rebound.SpringSystem(); this.spring=this.springSystem.createSpring(); this.spring.setRestSpeedThreshold(0.05); this.spring.setCurrentValue(0).setAtRest(); this.spring.addListener({ onSpringEndStateChange:function(){ if(!_this2._interactionHandle){ _this2._interactionHandle=_this2.createInteractionHandle();}}, onSpringUpdate:function(){ _this2._handleSpringUpdate();}, onSpringAtRest:function(){ _this2._completeTransition();}}); this.panGesture=PanResponder.create({ onMoveShouldSetPanResponder:this._handleMoveShouldSetPanResponder, onPanResponderRelease:this._handlePanResponderRelease, onPanResponderMove:this._handlePanResponderMove, onPanResponderTerminate:this._handlePanResponderTerminate}); this._interactionHandle=null; this._emitWillFocus(this.state.routeStack[this.state.presentedIndex]);}, componentDidMount:function(){ this._handleSpringUpdate(); this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]);}, componentWillUnmount:function(){ if(this._navigationContext){ this._navigationContext.dispose(); this._navigationContext=null;} this.spring.destroy(); if(this._interactionHandle){ this.clearInteractionHandle(this._interactionHandle);}}, immediatelyResetRouteStack:function(nextRouteStack){var _this3=this; var destIndex=nextRouteStack.length-1; this.setState({ routeStack:nextRouteStack, sceneConfigStack:nextRouteStack.map( this.props.configureScene), presentedIndex:destIndex, activeGesture:null, transitionFromIndex:null, transitionQueue:[]}, function(){ _this3._handleSpringUpdate();});}, _transitionTo:function(destIndex,velocity,jumpSpringTo,cb){ if(destIndex===this.state.presentedIndex){ return;} if(this.state.transitionFromIndex!==null){ this.state.transitionQueue.push({ destIndex:destIndex, velocity:velocity, cb:cb}); return;} this.state.transitionFromIndex=this.state.presentedIndex; this.state.presentedIndex=destIndex; this.state.transitionCb=cb; this._onAnimationStart(); if(AnimationsDebugModule){ AnimationsDebugModule.startRecordingFps();} var sceneConfig=this.state.sceneConfigStack[this.state.transitionFromIndex]|| this.state.sceneConfigStack[this.state.presentedIndex]; invariant( sceneConfig, 'Cannot configure scene at index '+this.state.transitionFromIndex); if(jumpSpringTo!=null){ this.spring.setCurrentValue(jumpSpringTo);} this.spring.setOvershootClampingEnabled(true); this.spring.getSpringConfig().friction=sceneConfig.springFriction; this.spring.getSpringConfig().tension=sceneConfig.springTension; this.spring.setVelocity(velocity||sceneConfig.defaultTransitionVelocity); this.spring.setEndValue(1);}, _handleSpringUpdate:function(){ if(!this.isMounted()){ return;} if(this.state.transitionFromIndex!=null){ this._transitionBetween( this.state.transitionFromIndex, this.state.presentedIndex, this.spring.getCurrentValue());}else if(this.state.activeGesture!=null){ var presentedToIndex=this.state.presentedIndex+this._deltaForGestureAction(this.state.activeGesture); this._transitionBetween( this.state.presentedIndex, presentedToIndex, this.spring.getCurrentValue());}}, _completeTransition:function(){ if(!this.isMounted()){ return;} if(this.spring.getCurrentValue()!==1&&this.spring.getCurrentValue()!==0){ if(this.state.pendingGestureProgress){ this.state.pendingGestureProgress=null;} return;} this._onAnimationEnd(); var presentedIndex=this.state.presentedIndex; var didFocusRoute=this._subRouteFocus[presentedIndex]||this.state.routeStack[presentedIndex]; this._emitDidFocus(didFocusRoute); if(AnimationsDebugModule){ AnimationsDebugModule.stopRecordingFps(Date.now());} this.state.transitionFromIndex=null; this.spring.setCurrentValue(0).setAtRest(); this._hideScenes(); if(this.state.transitionCb){ this.state.transitionCb(); this.state.transitionCb=null;} if(this._interactionHandle){ this.clearInteractionHandle(this._interactionHandle); this._interactionHandle=null;} if(this.state.pendingGestureProgress){ var gestureToIndex=this.state.presentedIndex+this._deltaForGestureAction(this.state.activeGesture); this._enableScene(gestureToIndex); this.spring.setEndValue(this.state.pendingGestureProgress); return;} if(this.state.transitionQueue.length){ var queuedTransition=this.state.transitionQueue.shift(); this._enableScene(queuedTransition.destIndex); this._emitWillFocus(this.state.routeStack[queuedTransition.destIndex]); this._transitionTo( queuedTransition.destIndex, queuedTransition.velocity, null, queuedTransition.cb);}}, _emitDidFocus:function(route){ this.navigationContext.emit('didfocus',{route:route}); if(this.props.onDidFocus){ this.props.onDidFocus(route);}}, _emitWillFocus:function(route){ this.navigationContext.emit('willfocus',{route:route}); var navBar=this._navBar; if(navBar&&navBar.handleWillFocus){ navBar.handleWillFocus(route);} if(this.props.onWillFocus){ this.props.onWillFocus(route);}}, _hideScenes:function(){ var gesturingToIndex=null; if(this.state.activeGesture){ gesturingToIndex=this.state.presentedIndex+this._deltaForGestureAction(this.state.activeGesture);} for(var i=0;i=this.state.routeStack.length-1&& gestureName==='jumpForward'; return wouldOverswipeForward||wouldOverswipeBack;}, _deltaForGestureAction:function(gestureAction){ switch(gestureAction){ case 'pop': case 'jumpBack': return -1; case 'jumpForward': return 1; default: invariant(false,'Unsupported gesture action '+gestureAction); return;}}, _handlePanResponderRelease:function(e,gestureState){var _this4=this; var sceneConfig=this.state.sceneConfigStack[this.state.presentedIndex]; var releaseGestureAction=this.state.activeGesture; if(!releaseGestureAction){ return;} var releaseGesture=sceneConfig.gestures[releaseGestureAction]; var destIndex=this.state.presentedIndex+this._deltaForGestureAction(this.state.activeGesture); if(this.spring.getCurrentValue()===0){ this.spring.setCurrentValue(0).setAtRest(); this._completeTransition(); return;} var isTravelVertical=releaseGesture.direction==='top-to-bottom'||releaseGesture.direction==='bottom-to-top'; var isTravelInverted=releaseGesture.direction==='right-to-left'||releaseGesture.direction==='bottom-to-top'; var velocity,gestureDistance; if(isTravelVertical){ velocity=isTravelInverted?-gestureState.vy:gestureState.vy; gestureDistance=isTravelInverted?-gestureState.dy:gestureState.dy;}else { velocity=isTravelInverted?-gestureState.vx:gestureState.vx; gestureDistance=isTravelInverted?-gestureState.dx:gestureState.dx;} var transitionVelocity=clamp(-10,velocity,10); if(Math.abs(velocity)releaseGesture.fullDistance*releaseGesture.stillCompletionRatio; transitionVelocity=hasGesturedEnoughToComplete?releaseGesture.snapVelocity:-releaseGesture.snapVelocity;} if(transitionVelocity<0||this._doesGestureOverswipe(releaseGestureAction)){ if(this.state.transitionFromIndex==null){ var transitionBackToPresentedIndex=this.state.presentedIndex; this.state.presentedIndex=destIndex; this._transitionTo( transitionBackToPresentedIndex, -transitionVelocity, 1-this.spring.getCurrentValue());}}else { this._emitWillFocus(this.state.routeStack[destIndex]); this._transitionTo( destIndex, transitionVelocity, null, function(){ if(releaseGestureAction==='pop'){ _this4._cleanScenesPastIndex(destIndex);}});} this._detachGesture();}, _handlePanResponderTerminate:function(e,gestureState){ if(this.state.activeGesture==null){ return;} var destIndex=this.state.presentedIndex+this._deltaForGestureAction(this.state.activeGesture); this._detachGesture(); var transitionBackToPresentedIndex=this.state.presentedIndex; this.state.presentedIndex=destIndex; this._transitionTo( transitionBackToPresentedIndex, null, 1-this.spring.getCurrentValue());}, _attachGesture:function(gestureId){ this.state.activeGesture=gestureId; var gesturingToIndex=this.state.presentedIndex+this._deltaForGestureAction(this.state.activeGesture); this._enableScene(gesturingToIndex);}, _detachGesture:function(){ this.state.activeGesture=null; this.state.pendingGestureProgress=null; this._hideScenes();}, _handlePanResponderMove:function(e,gestureState){ if(this._isMoveGestureAttached!==undefined){ invariant( this._expectingGestureGrant, 'Responder granted unexpectedly.'); this._attachGesture(this._expectingGestureGrant); this._onAnimationStart(); this._expectingGestureGrant=undefined;} var sceneConfig=this.state.sceneConfigStack[this.state.presentedIndex]; if(this.state.activeGesture){ var gesture=sceneConfig.gestures[this.state.activeGesture]; return this._moveAttachedGesture(gesture,gestureState);} var matchedGesture=this._matchGestureAction(GESTURE_ACTIONS,sceneConfig.gestures,gestureState); if(matchedGesture){ this._attachGesture(matchedGesture);}}, _moveAttachedGesture:function(gesture,gestureState){ var isTravelVertical=gesture.direction==='top-to-bottom'||gesture.direction==='bottom-to-top'; var isTravelInverted=gesture.direction==='right-to-left'||gesture.direction==='bottom-to-top'; var distance=isTravelVertical?gestureState.dy:gestureState.dx; distance=isTravelInverted?-distance:distance; var gestureDetectMovement=gesture.gestureDetectMovement; var nextProgress=(distance-gestureDetectMovement)/( gesture.fullDistance-gestureDetectMovement); if(nextProgress<0&&gesture.isDetachable){ var gesturingToIndex=this.state.presentedIndex+this._deltaForGestureAction(this.state.activeGesture); this._transitionBetween(this.state.presentedIndex,gesturingToIndex,0); this._detachGesture(); if(this.state.pendingGestureProgress!=null){ this.spring.setCurrentValue(0);} return;} if(this._doesGestureOverswipe(this.state.activeGesture)){ var frictionConstant=gesture.overswipe.frictionConstant; var frictionByDistance=gesture.overswipe.frictionByDistance; var frictionRatio=1/(frictionConstant+Math.abs(nextProgress)*frictionByDistance); nextProgress*=frictionRatio;} nextProgress=clamp(0,nextProgress,1); if(this.state.transitionFromIndex!=null){ this.state.pendingGestureProgress=nextProgress;}else if(this.state.pendingGestureProgress){ this.spring.setEndValue(nextProgress);}else { this.spring.setCurrentValue(nextProgress);}}, _matchGestureAction:function(eligibleGestures,gestures,gestureState){var _this5=this; if(!gestures){ return null;} var matchedGesture=null; eligibleGestures.some(function(gestureName,gestureIndex){ var gesture=gestures[gestureName]; if(!gesture){ return;} if(gesture.overswipe==null&&_this5._doesGestureOverswipe(gestureName)){ return false;} var isTravelVertical=gesture.direction==='top-to-bottom'||gesture.direction==='bottom-to-top'; var isTravelInverted=gesture.direction==='right-to-left'||gesture.direction==='bottom-to-top'; var currentLoc=isTravelVertical?gestureState.moveY:gestureState.moveX; var travelDist=isTravelVertical?gestureState.dy:gestureState.dx; var oppositeAxisTravelDist= isTravelVertical?gestureState.dx:gestureState.dy; var edgeHitWidth=gesture.edgeHitWidth; if(isTravelInverted){ currentLoc=-currentLoc; travelDist=-travelDist; oppositeAxisTravelDist=-oppositeAxisTravelDist; edgeHitWidth=isTravelVertical? -(SCREEN_HEIGHT-edgeHitWidth): -(SCREEN_WIDTH-edgeHitWidth);} var moveStartedInRegion=gesture.edgeHitWidth==null|| currentLoc=gesture.gestureDetectMovement; if(!moveTravelledFarEnough){ return false;} var directionIsCorrect=Math.abs(travelDist)>Math.abs(oppositeAxisTravelDist)*gesture.directionRatio; if(directionIsCorrect){ matchedGesture=gestureName; return true;}else { _this5._eligibleGestures=_this5._eligibleGestures.slice().splice(gestureIndex,1);}}); return matchedGesture||null;}, _transitionSceneStyle:function(fromIndex,toIndex,progress,index){ var viewAtIndex=this.refs['scene_'+index]; if(viewAtIndex===null||viewAtIndex===undefined){ return;} var sceneConfigIndex=fromIndex=0&&fromIndex>=0){ navBar.updateProgress(progress,fromIndex,toIndex);}}, _handleResponderTerminationRequest:function(){ return false;}, _getDestIndexWithinBounds:function(n){ var currentIndex=this.state.presentedIndex; var destIndex=currentIndex+n; invariant( destIndex>=0, 'Cannot jump before the first route.'); var maxIndex=this.state.routeStack.length-1; invariant( maxIndex>=destIndex, 'Cannot jump past the last route.'); return destIndex;}, _jumpN:function(n){ var destIndex=this._getDestIndexWithinBounds(n); this._enableScene(destIndex); this._emitWillFocus(this.state.routeStack[destIndex]); this._transitionTo(destIndex);}, jumpTo:function(route){ var destIndex=this.state.routeStack.indexOf(route); invariant( destIndex!==-1, 'Cannot jump to route that is not in the route stack'); this._jumpN(destIndex-this.state.presentedIndex);}, jumpForward:function(){ this._jumpN(1);}, jumpBack:function(){ this._jumpN(-1);}, push:function(route){var _this6=this; invariant(!!route,'Must supply route to push'); var activeLength=this.state.presentedIndex+1; var activeStack=this.state.routeStack.slice(0,activeLength); var activeAnimationConfigStack=this.state.sceneConfigStack.slice(0,activeLength); var nextStack=activeStack.concat([route]); var destIndex=nextStack.length-1; var nextAnimationConfigStack=activeAnimationConfigStack.concat([ this.props.configureScene(route)]); this._emitWillFocus(nextStack[destIndex]); this.setState({ routeStack:nextStack, sceneConfigStack:nextAnimationConfigStack}, function(){ _this6._enableScene(destIndex); _this6._transitionTo(destIndex);});}, _popN:function(n){var _this7=this; if(n===0){ return;} invariant( this.state.presentedIndex-n>=0, 'Cannot pop below zero'); var popIndex=this.state.presentedIndex-n; this._enableScene(popIndex); this._emitWillFocus(this.state.routeStack[popIndex]); this._transitionTo( popIndex, null, null, function(){ _this7._cleanScenesPastIndex(popIndex);});}, pop:function(){ if(this.state.transitionQueue.length){ return;} if(this.state.presentedIndex>0){ this._popN(1);}}, replaceAtIndex:function(route,index,cb){var _this8=this; invariant(!!route,'Must supply route to replace'); if(index<0){ index+=this.state.routeStack.length;} if(this.state.routeStack.length<=index){ return;} var nextRouteStack=this.state.routeStack.slice(); var nextAnimationModeStack=this.state.sceneConfigStack.slice(); nextRouteStack[index]=route; nextAnimationModeStack[index]=this.props.configureScene(route); if(index===this.state.presentedIndex){ this._emitWillFocus(route);} this.setState({ routeStack:nextRouteStack, sceneConfigStack:nextAnimationModeStack}, function(){ if(index===_this8.state.presentedIndex){ _this8._emitDidFocus(route);} cb&&cb();});}, replace:function(route){ this.replaceAtIndex(route,this.state.presentedIndex);}, replacePrevious:function(route){ this.replaceAtIndex(route,this.state.presentedIndex-1);}, popToTop:function(){ this.popToRoute(this.state.routeStack[0]);}, popToRoute:function(route){ var indexOfRoute=this.state.routeStack.indexOf(route); invariant( indexOfRoute!==-1, 'Calling popToRoute for a route that doesn\'t exist!'); var numToPop=this.state.presentedIndex-indexOfRoute; this._popN(numToPop);}, replacePreviousAndPop:function(route){ if(this.state.routeStack.length<2){ return;} this.replacePrevious(route); this.pop();}, resetTo:function(route){var _this9=this; invariant(!!route,'Must supply route to push'); this.replaceAtIndex(route,0,function(){ if(_this9.state.presentedIndex>0){ _this9._popN(_this9.state.presentedIndex);}});}, getCurrentRoutes:function(){ return this.state.routeStack.slice();}, _cleanScenesPastIndex:function(index){ var newStackLength=index+1; if(newStackLength0){ var args=Array.prototype.slice.call(arguments); this._emitQueue.push(args); return;} this._emitCounter++; if(LegacyEventTypes.has(eventType)){ this.__emit( eventType, data, null, { defaultPrevented:false, eventPhase:AT_TARGET, propagationStopped:true, target:this});}else { var targets=[this]; var parentTarget=this.parent; while(parentTarget){ targets.unshift(parentTarget); parentTarget=parentTarget.parent;} var propagationStopped=false; var defaultPrevented=false; var callback=function(event){ propagationStopped=propagationStopped||event.isPropagationStopped(); defaultPrevented=defaultPrevented||event.defaultPrevented;}; targets.some(function(currentTarget){ if(propagationStopped){ return true;} var extraInfo={ defaultPrevented:defaultPrevented, eventPhase:CAPTURING_PHASE, propagationStopped:propagationStopped, target:_this}; currentTarget.__emit(eventType,data,callback,extraInfo);}, this); targets.reverse().some(function(currentTarget){ if(propagationStopped){ return true;} var extraInfo={ defaultPrevented:defaultPrevented, eventPhase:BUBBLING_PHASE, propagationStopped:propagationStopped, target:_this}; currentTarget.__emit(eventType,data,callback,extraInfo);}, this);} if(didEmitCallback){ var event=NavigationEvent.pool(eventType,this,data); propagationStopped&&event.stopPropagation(); defaultPrevented&&event.preventDefault(); didEmitCallback.call(this,event); event.dispose();} this._emitCounter--; while(this._emitQueue.length){ var args=this._emitQueue.shift(); this.emit.apply(this,args);}}},{key:'dispose',value:function dispose() { this._bubbleEventEmitter&&this._bubbleEventEmitter.removeAllListeners(); this._captureEventEmitter&&this._captureEventEmitter.removeAllListeners(); this._bubbleEventEmitter=null; this._captureEventEmitter=null; this._currentRoute=null;}},{key:'__emit',value:function __emit( eventType, data, didEmitCallback, extraInfo) { var emitter; switch(extraInfo.eventPhase){ case CAPTURING_PHASE: emitter=this._captureEventEmitter; break; case AT_TARGET: emitter=this._bubbleEventEmitter; break; case BUBBLING_PHASE: emitter=this._bubbleEventEmitter; break; default: invariant(false,'invalid event phase %s',extraInfo.eventPhase);} if(extraInfo.target===this){ extraInfo.eventPhase=AT_TARGET;} if(emitter){ emitter.emit( eventType, data, didEmitCallback, extraInfo);}}},{key:'_onFocus',value:function _onFocus( event){ invariant( event.data&&event.data.hasOwnProperty('route'), 'event type "%s" should provide route', event.type); this._currentRoute=event.data.route;}},{key:'parent',get:function(){var parent=this.__node.getParent();return parent?parent.getValue():null;}},{key:'top',get:function(){var result=null;var parentNode=this.__node.getParent();while(parentNode){result=parentNode.getValue();parentNode=parentNode.getParent();}return result;}},{key:'currentRoute',get:function(){return this._currentRoute;}}]);return NavigationContext;})(); module.exports=NavigationContext; }); __d('NavigationEvent',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant');var NavigationEventPool=(function(){ function NavigationEventPool(){babelHelpers.classCallCheck(this,NavigationEventPool); this._list=[];}babelHelpers.createClass(NavigationEventPool,[{key:'get',value:function get( type,currentTarget,data){ var event; if(this._list.length>0){ event=this._list.pop(); event.constructor.call(event,type,currentTarget,data);}else { event=new NavigationEvent(type,currentTarget,data);} return event;}},{key:'put',value:function put( event){ this._list.push(event);}}]);return NavigationEventPool;})(); var _navigationEventPool=new NavigationEventPool();var NavigationEvent=(function(){babelHelpers.createClass(NavigationEvent,null,[{key:'pool',value:function pool( type,currentTarget,data){ return _navigationEventPool.get(type,currentTarget,data);}}]); function NavigationEvent(type,currentTarget,data){babelHelpers.classCallCheck(this,NavigationEvent); this.target=currentTarget; this.eventPhase=NavigationEvent.NONE; this._type=type; this._currentTarget=currentTarget; this._data=data; this._defaultPrevented=false; this._disposed=false; this._propagationStopped=false;}babelHelpers.createClass(NavigationEvent,[{key:'preventDefault',value:function preventDefault() { this._defaultPrevented=true;}},{key:'stopPropagation',value:function stopPropagation() { this._propagationStopped=true;}},{key:'stop',value:function stop() { this.preventDefault(); this.stopPropagation();}},{key:'isPropagationStopped',value:function isPropagationStopped() { return this._propagationStopped;}},{key:'dispose',value:function dispose() { invariant(!this._disposed,'NavigationEvent is already disposed'); this._disposed=true; this.target=null; this.eventPhase=NavigationEvent.NONE; this._type=null; this._currentTarget=null; this._data=null; this._defaultPrevented=false; _navigationEventPool.put(this);}},{key:'type',get:function(){return this._type;}},{key:'currentTarget',get:function(){return this._currentTarget;}},{key:'data',get:function(){return this._data;}},{key:'defaultPrevented',get:function(){return this._defaultPrevented;}}]);return NavigationEvent;})(); NavigationEvent.NONE=0; NavigationEvent.CAPTURING_PHASE=1; NavigationEvent.AT_TARGET=2; NavigationEvent.BUBBLING_PHASE=3; module.exports=NavigationEvent; }); __d('NavigationEventEmitter',function(global, require, module, exports) { 'use strict'; var EventEmitter=require('EventEmitter'); var NavigationEvent=require('NavigationEvent');var NavigationEventEmitter=(function(_EventEmitter){babelHelpers.inherits(NavigationEventEmitter,_EventEmitter); function NavigationEventEmitter(target){babelHelpers.classCallCheck(this,NavigationEventEmitter);var _this=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(NavigationEventEmitter).call(this)); _this._emitting=false; _this._emitQueue=[]; _this._target=target;return _this;}babelHelpers.createClass(NavigationEventEmitter,[{key:'emit',value:function emit( eventType, data, didEmitCallback, extraInfo) { if(this._emitting){ var args=Array.prototype.slice.call(arguments); this._emitQueue.unshift(args); return;} this._emitting=true; var event=NavigationEvent.pool(eventType,this._target,data); if(extraInfo){ if(extraInfo.target){ event.target=extraInfo.target;} if(extraInfo.eventPhase){ event.eventPhase=extraInfo.eventPhase;} if(extraInfo.defaultPrevented){ event.preventDefault();} if(extraInfo.propagationStopped){ event.stopPropagation();}} babelHelpers.get(Object.getPrototypeOf(NavigationEventEmitter.prototype),'emit',this).call(this,String(eventType),event); if(typeof didEmitCallback==='function'){ didEmitCallback.call(this._target,event);} event.dispose(); this._emitting=false; while(this._emitQueue.length){ var args=this._emitQueue.shift(); this.emit.apply(this,args);}}}]);return NavigationEventEmitter;})(EventEmitter); module.exports=NavigationEventEmitter; }); __d('NavigationTreeNode',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var immutable=require('immutable/dist/immutable.js');var List=immutable.List;var NavigationTreeNode=(function(){ function NavigationTreeNode(value){babelHelpers.classCallCheck(this,NavigationTreeNode); this.__parent=null; this._children=new List(); this._value=value;}babelHelpers.createClass(NavigationTreeNode,[{key:'getValue',value:function getValue() { return this._value;}},{key:'getParent',value:function getParent() { return this.__parent;}},{key:'getChildrenCount',value:function getChildrenCount() { return this._children.size;}},{key:'getChildAt',value:function getChildAt( index){ return index>-1&&index-1, 'The node to be removed is not a child of this node.'); child.__parent=null; this._children=this._children.splice(index,1);}},{key:'indexOf',value:function indexOf( child){ return this._children.indexOf(child);}},{key:'forEach',value:function forEach( callback,context){ this._children.forEach(callback,context);}},{key:'map',value:function map( callback,context){ return this._children.map(callback,context).toJS();}},{key:'some',value:function some( callback,context){ return this._children.some(callback,context);}}]);return NavigationTreeNode;})(); module.exports=NavigationTreeNode; }); __d('immutable/dist/immutable.js',function(global, require, module, exports) { ( function(global,factory){ typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory(): typeof define==='function'&&define.amd?define(factory): global.Immutable=factory();})( this,function(){'use strict';var SLICE$0=Array.prototype.slice; function createClass(ctor,superClass){ if(superClass){ ctor.prototype=Object.create(superClass.prototype);} ctor.prototype.constructor=ctor;} function Iterable(value){ return isIterable(value)?value:Seq(value);} createClass(KeyedIterable,Iterable); function KeyedIterable(value){ return isKeyed(value)?value:KeyedSeq(value);} createClass(IndexedIterable,Iterable); function IndexedIterable(value){ return isIndexed(value)?value:IndexedSeq(value);} createClass(SetIterable,Iterable); function SetIterable(value){ return isIterable(value)&&!isAssociative(value)?value:SetSeq(value);} function isIterable(maybeIterable){ return !!(maybeIterable&&maybeIterable[IS_ITERABLE_SENTINEL]);} function isKeyed(maybeKeyed){ return !!(maybeKeyed&&maybeKeyed[IS_KEYED_SENTINEL]);} function isIndexed(maybeIndexed){ return !!(maybeIndexed&&maybeIndexed[IS_INDEXED_SENTINEL]);} function isAssociative(maybeAssociative){ return isKeyed(maybeAssociative)||isIndexed(maybeAssociative);} function isOrdered(maybeOrdered){ return !!(maybeOrdered&&maybeOrdered[IS_ORDERED_SENTINEL]);} Iterable.isIterable=isIterable; Iterable.isKeyed=isKeyed; Iterable.isIndexed=isIndexed; Iterable.isAssociative=isAssociative; Iterable.isOrdered=isOrdered; Iterable.Keyed=KeyedIterable; Iterable.Indexed=IndexedIterable; Iterable.Set=SetIterable; var IS_ITERABLE_SENTINEL='@@__IMMUTABLE_ITERABLE__@@'; var IS_KEYED_SENTINEL='@@__IMMUTABLE_KEYED__@@'; var IS_INDEXED_SENTINEL='@@__IMMUTABLE_INDEXED__@@'; var IS_ORDERED_SENTINEL='@@__IMMUTABLE_ORDERED__@@'; var DELETE='delete'; var SHIFT=5; var SIZE=1<>>0; if(''+uint32Index!==index||uint32Index===4294967295){ return NaN;} index=uint32Index;} return index<0?ensureSize(iter)+index:index;} function returnTrue(){ return true;} function wholeSlice(begin,end,size){ return (begin===0||size!==undefined&&begin<=-size)&&( end===undefined||size!==undefined&&end>=size);} function resolveBegin(begin,size){ return resolveIndex(begin,size,0);} function resolveEnd(end,size){ return resolveIndex(end,size,size);} function resolveIndex(index,size,defaultIndex){ return index===undefined? defaultIndex: index<0? Math.max(0,size+index): size===undefined? index: Math.min(size,index);} var ITERATE_KEYS=0; var ITERATE_VALUES=1; var ITERATE_ENTRIES=2; var REAL_ITERATOR_SYMBOL=typeof Symbol==='function'&&Symbol.iterator; var FAUX_ITERATOR_SYMBOL='@@iterator'; var ITERATOR_SYMBOL=REAL_ITERATOR_SYMBOL||FAUX_ITERATOR_SYMBOL; function Iterator(next){ this.next=next;} Iterator.prototype.toString=function(){ return '[Iterator]';}; Iterator.KEYS=ITERATE_KEYS; Iterator.VALUES=ITERATE_VALUES; Iterator.ENTRIES=ITERATE_ENTRIES; Iterator.prototype.inspect= Iterator.prototype.toSource=function(){return this.toString();}; Iterator.prototype[ITERATOR_SYMBOL]=function(){ return this;}; function iteratorValue(type,k,v,iteratorResult){ var value=type===0?k:type===1?v:[k,v]; iteratorResult?iteratorResult.value=value:iteratorResult={ value:value,done:false}; return iteratorResult;} function iteratorDone(){ return {value:undefined,done:true};} function hasIterator(maybeIterable){ return !!getIteratorFn(maybeIterable);} function isIterator(maybeIterator){ return maybeIterator&&typeof maybeIterator.next==='function';} function getIterator(iterable){ var iteratorFn=getIteratorFn(iterable); return iteratorFn&&iteratorFn.call(iterable);} function getIteratorFn(iterable){ var iteratorFn=iterable&&( REAL_ITERATOR_SYMBOL&&iterable[REAL_ITERATOR_SYMBOL]|| iterable[FAUX_ITERATOR_SYMBOL]); if(typeof iteratorFn==='function'){ return iteratorFn;}} function isArrayLike(value){ return value&&typeof value.length==='number';} createClass(Seq,Iterable); function Seq(value){ return value===null||value===undefined?emptySequence(): isIterable(value)?value.toSeq():seqFromValue(value);} Seq.of=function(){ return Seq(arguments);}; Seq.prototype.toSeq=function(){ return this;}; Seq.prototype.toString=function(){ return this.__toString('Seq {','}');}; Seq.prototype.cacheResult=function(){ if(!this._cache&&this.__iterateUncached){ this._cache=this.entrySeq().toArray(); this.size=this._cache.length;} return this;}; Seq.prototype.__iterate=function(fn,reverse){ return seqIterate(this,fn,reverse,true);}; Seq.prototype.__iterator=function(type,reverse){ return seqIterator(this,type,reverse,true);}; createClass(KeyedSeq,Seq); function KeyedSeq(value){ return value===null||value===undefined? emptySequence().toKeyedSeq(): isIterable(value)? isKeyed(value)?value.toSeq():value.fromEntrySeq(): keyedSeqFromValue(value);} KeyedSeq.prototype.toKeyedSeq=function(){ return this;}; createClass(IndexedSeq,Seq); function IndexedSeq(value){ return value===null||value===undefined?emptySequence(): !isIterable(value)?indexedSeqFromValue(value): isKeyed(value)?value.entrySeq():value.toIndexedSeq();} IndexedSeq.of=function(){ return IndexedSeq(arguments);}; IndexedSeq.prototype.toIndexedSeq=function(){ return this;}; IndexedSeq.prototype.toString=function(){ return this.__toString('Seq [',']');}; IndexedSeq.prototype.__iterate=function(fn,reverse){ return seqIterate(this,fn,reverse,false);}; IndexedSeq.prototype.__iterator=function(type,reverse){ return seqIterator(this,type,reverse,false);}; createClass(SetSeq,Seq); function SetSeq(value){ return ( value===null||value===undefined?emptySequence(): !isIterable(value)?indexedSeqFromValue(value): isKeyed(value)?value.entrySeq():value). toSetSeq();} SetSeq.of=function(){ return SetSeq(arguments);}; SetSeq.prototype.toSetSeq=function(){ return this;}; Seq.isSeq=isSeq; Seq.Keyed=KeyedSeq; Seq.Set=SetSeq; Seq.Indexed=IndexedSeq; var IS_SEQ_SENTINEL='@@__IMMUTABLE_SEQ__@@'; Seq.prototype[IS_SEQ_SENTINEL]=true; createClass(ArraySeq,IndexedSeq); function ArraySeq(array){ this._array=array; this.size=array.length;} ArraySeq.prototype.get=function(index,notSetValue){ return this.has(index)?this._array[wrapIndex(this,index)]:notSetValue;}; ArraySeq.prototype.__iterate=function(fn,reverse){ var array=this._array; var maxIndex=array.length-1; for(var ii=0;ii<=maxIndex;ii++){ if(fn(array[reverse?maxIndex-ii:ii],ii,this)===false){ return ii+1;}} return ii;}; ArraySeq.prototype.__iterator=function(type,reverse){ var array=this._array; var maxIndex=array.length-1; var ii=0; return new Iterator(function() {return ii>maxIndex? iteratorDone(): iteratorValue(type,ii,array[reverse?maxIndex-ii++:ii++]);});}; createClass(ObjectSeq,KeyedSeq); function ObjectSeq(object){ var keys=Object.keys(object); this._object=object; this._keys=keys; this.size=keys.length;} ObjectSeq.prototype.get=function(key,notSetValue){ if(notSetValue!==undefined&&!this.has(key)){ return notSetValue;} return this._object[key];}; ObjectSeq.prototype.has=function(key){ return this._object.hasOwnProperty(key);}; ObjectSeq.prototype.__iterate=function(fn,reverse){ var object=this._object; var keys=this._keys; var maxIndex=keys.length-1; for(var ii=0;ii<=maxIndex;ii++){ var key=keys[reverse?maxIndex-ii:ii]; if(fn(object[key],key,this)===false){ return ii+1;}} return ii;}; ObjectSeq.prototype.__iterator=function(type,reverse){ var object=this._object; var keys=this._keys; var maxIndex=keys.length-1; var ii=0; return new Iterator(function(){ var key=keys[reverse?maxIndex-ii:ii]; return ii++>maxIndex? iteratorDone(): iteratorValue(type,key,object[key]);});}; ObjectSeq.prototype[IS_ORDERED_SENTINEL]=true; createClass(IterableSeq,IndexedSeq); function IterableSeq(iterable){ this._iterable=iterable; this.size=iterable.length||iterable.size;} IterableSeq.prototype.__iterateUncached=function(fn,reverse){ if(reverse){ return this.cacheResult().__iterate(fn,reverse);} var iterable=this._iterable; var iterator=getIterator(iterable); var iterations=0; if(isIterator(iterator)){ var step; while(!(step=iterator.next()).done){ if(fn(step.value,iterations++,this)===false){ break;}}} return iterations;}; IterableSeq.prototype.__iteratorUncached=function(type,reverse){ if(reverse){ return this.cacheResult().__iterator(type,reverse);} var iterable=this._iterable; var iterator=getIterator(iterable); if(!isIterator(iterator)){ return new Iterator(iteratorDone);} var iterations=0; return new Iterator(function(){ var step=iterator.next(); return step.done?step:iteratorValue(type,iterations++,step.value);});}; createClass(IteratorSeq,IndexedSeq); function IteratorSeq(iterator){ this._iterator=iterator; this._iteratorCache=[];} IteratorSeq.prototype.__iterateUncached=function(fn,reverse){ if(reverse){ return this.cacheResult().__iterate(fn,reverse);} var iterator=this._iterator; var cache=this._iteratorCache; var iterations=0; while(iterations=cache.length){ var step=iterator.next(); if(step.done){ return step;} cache[iterations]=step.value;} return iteratorValue(type,iterations,cache[iterations++]);});}; function isSeq(maybeSeq){ return !!(maybeSeq&&maybeSeq[IS_SEQ_SENTINEL]);} var EMPTY_SEQ; function emptySequence(){ return EMPTY_SEQ||(EMPTY_SEQ=new ArraySeq([]));} function keyedSeqFromValue(value){ var seq= Array.isArray(value)?new ArraySeq(value).fromEntrySeq(): isIterator(value)?new IteratorSeq(value).fromEntrySeq(): hasIterator(value)?new IterableSeq(value).fromEntrySeq(): typeof value==='object'?new ObjectSeq(value): undefined; if(!seq){ throw new TypeError( 'Expected Array or iterable object of [k, v] entries, '+ 'or keyed object: '+value);} return seq;} function indexedSeqFromValue(value){ var seq=maybeIndexedSeqFromValue(value); if(!seq){ throw new TypeError( 'Expected Array or iterable object of values: '+value);} return seq;} function seqFromValue(value){ var seq=maybeIndexedSeqFromValue(value)|| typeof value==='object'&&new ObjectSeq(value); if(!seq){ throw new TypeError( 'Expected Array or iterable object of values, or keyed object: '+value);} return seq;} function maybeIndexedSeqFromValue(value){ return ( isArrayLike(value)?new ArraySeq(value): isIterator(value)?new IteratorSeq(value): hasIterator(value)?new IterableSeq(value): undefined);} function seqIterate(seq,fn,reverse,useKeys){ var cache=seq._cache; if(cache){ var maxIndex=cache.length-1; for(var ii=0;ii<=maxIndex;ii++){ var entry=cache[reverse?maxIndex-ii:ii]; if(fn(entry[1],useKeys?entry[0]:ii,seq)===false){ return ii+1;}} return ii;} return seq.__iterateUncached(fn,reverse);} function seqIterator(seq,type,reverse,useKeys){ var cache=seq._cache; if(cache){ var maxIndex=cache.length-1; var ii=0; return new Iterator(function(){ var entry=cache[reverse?maxIndex-ii:ii]; return ii++>maxIndex? iteratorDone(): iteratorValue(type,useKeys?entry[0]:ii-1,entry[1]);});} return seq.__iteratorUncached(type,reverse);} function fromJS(json,converter){ return converter? fromJSWith(converter,json,'',{'':json}): fromJSDefault(json);} function fromJSWith(converter,json,key,parentJSON){ if(Array.isArray(json)){ return converter.call(parentJSON,key,IndexedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json);}));} if(isPlainObj(json)){ return converter.call(parentJSON,key,KeyedSeq(json).map(function(v,k){return fromJSWith(converter,v,k,json);}));} return json;} function fromJSDefault(json){ if(Array.isArray(json)){ return IndexedSeq(json).map(fromJSDefault).toList();} if(isPlainObj(json)){ return KeyedSeq(json).map(fromJSDefault).toMap();} return json;} function isPlainObj(value){ return value&&(value.constructor===Object||value.constructor===undefined);} function is(valueA,valueB){ if(valueA===valueB||valueA!==valueA&&valueB!==valueB){ return true;} if(!valueA||!valueB){ return false;} if(typeof valueA.valueOf==='function'&& typeof valueB.valueOf==='function'){ valueA=valueA.valueOf(); valueB=valueB.valueOf(); if(valueA===valueB||valueA!==valueA&&valueB!==valueB){ return true;} if(!valueA||!valueB){ return false;}} if(typeof valueA.equals==='function'&& typeof valueB.equals==='function'&& valueA.equals(valueB)){ return true;} return false;} function deepEqual(a,b){ if(a===b){ return true;} if( !isIterable(b)|| a.size!==undefined&&b.size!==undefined&&a.size!==b.size|| a.__hash!==undefined&&b.__hash!==undefined&&a.__hash!==b.__hash|| isKeyed(a)!==isKeyed(b)|| isIndexed(a)!==isIndexed(b)|| isOrdered(a)!==isOrdered(b)) { return false;} if(a.size===0&&b.size===0){ return true;} var notAssociative=!isAssociative(a); if(isOrdered(a)){ var entries=a.entries(); return b.every(function(v,k){ var entry=entries.next().value; return entry&&is(entry[1],v)&&(notAssociative||is(entry[0],k));})&& entries.next().done;} var flipped=false; if(a.size===undefined){ if(b.size===undefined){ if(typeof a.cacheResult==='function'){ a.cacheResult();}}else { flipped=true; var _=a; a=b; b=_;}} var allEqual=true; var bSize=b.__iterate(function(v,k){ if(notAssociative?!a.has(v): flipped?!is(v,a.get(k,NOT_SET)):!is(a.get(k,NOT_SET),v)){ allEqual=false; return false;}}); return allEqual&&a.size===bSize;} createClass(Repeat,IndexedSeq); function Repeat(value,times){ if(!(this instanceof Repeat)){ return new Repeat(value,times);} this._value=value; this.size=times===undefined?Infinity:Math.max(0,times); if(this.size===0){ if(EMPTY_REPEAT){ return EMPTY_REPEAT;} EMPTY_REPEAT=this;}} Repeat.prototype.toString=function(){ if(this.size===0){ return 'Repeat []';} return 'Repeat [ '+this._value+' '+this.size+' times ]';}; Repeat.prototype.get=function(index,notSetValue){ return this.has(index)?this._value:notSetValue;}; Repeat.prototype.includes=function(searchValue){ return is(this._value,searchValue);}; Repeat.prototype.slice=function(begin,end){ var size=this.size; return wholeSlice(begin,end,size)?this: new Repeat(this._value,resolveEnd(end,size)-resolveBegin(begin,size));}; Repeat.prototype.reverse=function(){ return this;}; Repeat.prototype.indexOf=function(searchValue){ if(is(this._value,searchValue)){ return 0;} return -1;}; Repeat.prototype.lastIndexOf=function(searchValue){ if(is(this._value,searchValue)){ return this.size;} return -1;}; Repeat.prototype.__iterate=function(fn,reverse){ for(var ii=0;ii1?' by '+this._step:'')+ ' ]';}; Range.prototype.get=function(index,notSetValue){ return this.has(index)? this._start+wrapIndex(this,index)*this._step: notSetValue;}; Range.prototype.includes=function(searchValue){ var possibleIndex=(searchValue-this._start)/this._step; return possibleIndex>=0&& possibleIndex=0&&indexmaxIndex?iteratorDone():iteratorValue(type,ii++,v);});}; Range.prototype.equals=function(other){ return other instanceof Range? this._start===other._start&& this._end===other._end&& this._step===other._step: deepEqual(this,other);}; var EMPTY_RANGE; createClass(Collection,Iterable); function Collection(){ throw TypeError('Abstract');} createClass(KeyedCollection,Collection);function KeyedCollection(){} createClass(IndexedCollection,Collection);function IndexedCollection(){} createClass(SetCollection,Collection);function SetCollection(){} Collection.Keyed=KeyedCollection; Collection.Indexed=IndexedCollection; Collection.Set=SetCollection; var imul= typeof Math.imul==='function'&&Math.imul(0xffffffff,2)===-2? Math.imul: function imul(a,b){ a=a|0; b=b|0; var c=a&0xffff; var d=b&0xffff; return c*d+((a>>>16)*d+c*(b>>>16)<<16>>>0)|0;}; function smi(i32){ return i32>>>1&0x40000000|i32&0xBFFFFFFF;} function hash(o){ if(o===false||o===null||o===undefined){ return 0;} if(typeof o.valueOf==='function'){ o=o.valueOf(); if(o===false||o===null||o===undefined){ return 0;}} if(o===true){ return 1;} var type=typeof o; if(type==='number'){ var h=o|0; if(h!==o){ h^=o*0xFFFFFFFF;} while(o>0xFFFFFFFF){ o/=0xFFFFFFFF; h^=o;} return smi(h);} if(type==='string'){ return o.length>STRING_HASH_CACHE_MIN_STRLEN?cachedHashString(o):hashString(o);} if(typeof o.hashCode==='function'){ return o.hashCode();} if(type==='object'){ return hashJSObj(o);} if(typeof o.toString==='function'){ return hashString(o.toString());} throw new Error('Value type '+type+' cannot be hashed.');} function cachedHashString(string){ var hash=stringHashCache[string]; if(hash===undefined){ hash=hashString(string); if(STRING_HASH_CACHE_SIZE===STRING_HASH_CACHE_MAX_SIZE){ STRING_HASH_CACHE_SIZE=0; stringHashCache={};} STRING_HASH_CACHE_SIZE++; stringHashCache[string]=hash;} return hash;} function hashString(string){ var hash=0; for(var ii=0;ii0){ switch(node.nodeType){ case 1: return node.uniqueID; case 9: return node.documentElement&&node.documentElement.uniqueID;}}} var usingWeakMap=typeof WeakMap==='function'; var weakMap; if(usingWeakMap){ weakMap=new WeakMap();} var objHashUID=0; var UID_HASH_KEY='__immutablehash__'; if(typeof Symbol==='function'){ UID_HASH_KEY=Symbol(UID_HASH_KEY);} var STRING_HASH_CACHE_MIN_STRLEN=16; var STRING_HASH_CACHE_MAX_SIZE=255; var STRING_HASH_CACHE_SIZE=0; var stringHashCache={}; function assertNotInfinite(size){ invariant( size!==Infinity, 'Cannot perform this action with an infinite size.');} createClass(Map,KeyedCollection); function Map(value){ return value===null||value===undefined?emptyMap(): isMap(value)&&!isOrdered(value)?value: emptyMap().withMutations(function(map){ var iter=KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v,k){return map.set(k,v);});});} Map.prototype.toString=function(){ return this.__toString('Map {','}');}; Map.prototype.get=function(k,notSetValue){ return this._root? this._root.get(0,undefined,k,notSetValue): notSetValue;}; Map.prototype.set=function(k,v){ return updateMap(this,k,v);}; Map.prototype.setIn=function(keyPath,v){ return this.updateIn(keyPath,NOT_SET,function(){return v;});}; Map.prototype.remove=function(k){ return updateMap(this,k,NOT_SET);}; Map.prototype.deleteIn=function(keyPath){ return this.updateIn(keyPath,function(){return NOT_SET;});}; Map.prototype.update=function(k,notSetValue,updater){ return arguments.length===1? k(this): this.updateIn([k],notSetValue,updater);}; Map.prototype.updateIn=function(keyPath,notSetValue,updater){ if(!updater){ updater=notSetValue; notSetValue=undefined;} var updatedValue=updateInDeepMap( this, forceIterator(keyPath), notSetValue, updater); return updatedValue===NOT_SET?undefined:updatedValue;}; Map.prototype.clear=function(){ if(this.size===0){ return this;} if(this.__ownerID){ this.size=0; this._root=null; this.__hash=undefined; this.__altered=true; return this;} return emptyMap();}; Map.prototype.merge=function(){ return mergeIntoMapWith(this,undefined,arguments);}; Map.prototype.mergeWith=function(merger){var iters=SLICE$0.call(arguments,1); return mergeIntoMapWith(this,merger,iters);}; Map.prototype.mergeIn=function(keyPath){var iters=SLICE$0.call(arguments,1); return this.updateIn( keyPath, emptyMap(), function(m){return typeof m.merge==='function'? m.merge.apply(m,iters): iters[iters.length-1];});}; Map.prototype.mergeDeep=function(){ return mergeIntoMapWith(this,deepMerger,arguments);}; Map.prototype.mergeDeepWith=function(merger){var iters=SLICE$0.call(arguments,1); return mergeIntoMapWith(this,deepMergerWith(merger),iters);}; Map.prototype.mergeDeepIn=function(keyPath){var iters=SLICE$0.call(arguments,1); return this.updateIn( keyPath, emptyMap(), function(m){return typeof m.mergeDeep==='function'? m.mergeDeep.apply(m,iters): iters[iters.length-1];});}; Map.prototype.sort=function(comparator){ return OrderedMap(sortFactory(this,comparator));}; Map.prototype.sortBy=function(mapper,comparator){ return OrderedMap(sortFactory(this,comparator,mapper));}; Map.prototype.withMutations=function(fn){ var mutable=this.asMutable(); fn(mutable); return mutable.wasAltered()?mutable.__ensureOwner(this.__ownerID):this;}; Map.prototype.asMutable=function(){ return this.__ownerID?this:this.__ensureOwner(new OwnerID());}; Map.prototype.asImmutable=function(){ return this.__ensureOwner();}; Map.prototype.wasAltered=function(){ return this.__altered;}; Map.prototype.__iterator=function(type,reverse){ return new MapIterator(this,type,reverse);}; Map.prototype.__iterate=function(fn,reverse){var this$0=this; var iterations=0; this._root&&this._root.iterate(function(entry){ iterations++; return fn(entry[1],entry[0],this$0);}, reverse); return iterations;}; Map.prototype.__ensureOwner=function(ownerID){ if(ownerID===this.__ownerID){ return this;} if(!ownerID){ this.__ownerID=ownerID; this.__altered=false; return this;} return makeMap(this.size,this._root,ownerID,this.__hash);}; function isMap(maybeMap){ return !!(maybeMap&&maybeMap[IS_MAP_SENTINEL]);} Map.isMap=isMap; var IS_MAP_SENTINEL='@@__IMMUTABLE_MAP__@@'; var MapPrototype=Map.prototype; MapPrototype[IS_MAP_SENTINEL]=true; MapPrototype[DELETE]=MapPrototype.remove; MapPrototype.removeIn=MapPrototype.deleteIn; function ArrayMapNode(ownerID,entries){ this.ownerID=ownerID; this.entries=entries;} ArrayMapNode.prototype.get=function(shift,keyHash,key,notSetValue){ var entries=this.entries; for(var ii=0,len=entries.length;ii=MAX_ARRAY_MAP_SIZE){ return createNodes(ownerID,entries,key,value);} var isEditable=ownerID&&ownerID===this.ownerID; var newEntries=isEditable?entries:arrCopy(entries); if(exists){ if(removed){ idx===len-1?newEntries.pop():newEntries[idx]=newEntries.pop();}else { newEntries[idx]=[key,value];}}else { newEntries.push([key,value]);} if(isEditable){ this.entries=newEntries; return this;} return new ArrayMapNode(ownerID,newEntries);}; function BitmapIndexedNode(ownerID,bitmap,nodes){ this.ownerID=ownerID; this.bitmap=bitmap; this.nodes=nodes;} BitmapIndexedNode.prototype.get=function(shift,keyHash,key,notSetValue){ if(keyHash===undefined){ keyHash=hash(key);} var bit=1<<((shift===0?keyHash:keyHash>>>shift)&MASK); var bitmap=this.bitmap; return (bitmap&bit)===0?notSetValue: this.nodes[popCount(bitmap&bit-1)].get(shift+SHIFT,keyHash,key,notSetValue);}; BitmapIndexedNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){ if(keyHash===undefined){ keyHash=hash(key);} var keyHashFrag=(shift===0?keyHash:keyHash>>>shift)&MASK; var bit=1<=MAX_BITMAP_INDEXED_SIZE){ return expandNodes(ownerID,nodes,bitmap,keyHashFrag,newNode);} if(exists&&!newNode&&nodes.length===2&&isLeafNode(nodes[idx^1])){ return nodes[idx^1];} if(exists&&newNode&&nodes.length===1&&isLeafNode(newNode)){ return newNode;} var isEditable=ownerID&&ownerID===this.ownerID; var newBitmap=exists?newNode?bitmap:bitmap^bit:bitmap|bit; var newNodes=exists?newNode? setIn(nodes,idx,newNode,isEditable): spliceOut(nodes,idx,isEditable): spliceIn(nodes,idx,newNode,isEditable); if(isEditable){ this.bitmap=newBitmap; this.nodes=newNodes; return this;} return new BitmapIndexedNode(ownerID,newBitmap,newNodes);}; function HashArrayMapNode(ownerID,count,nodes){ this.ownerID=ownerID; this.count=count; this.nodes=nodes;} HashArrayMapNode.prototype.get=function(shift,keyHash,key,notSetValue){ if(keyHash===undefined){ keyHash=hash(key);} var idx=(shift===0?keyHash:keyHash>>>shift)&MASK; var node=this.nodes[idx]; return node?node.get(shift+SHIFT,keyHash,key,notSetValue):notSetValue;}; HashArrayMapNode.prototype.update=function(ownerID,shift,keyHash,key,value,didChangeSize,didAlter){ if(keyHash===undefined){ keyHash=hash(key);} var idx=(shift===0?keyHash:keyHash>>>shift)&MASK; var removed=value===NOT_SET; var nodes=this.nodes; var node=nodes[idx]; if(removed&&!node){ return this;} var newNode=updateNode(node,ownerID,shift+SHIFT,keyHash,key,value,didChangeSize,didAlter); if(newNode===node){ return this;} var newCount=this.count; if(!node){ newCount++;}else if(!newNode){ newCount--; if(newCount>>shift)&MASK; var idx2=(shift===0?keyHash:keyHash>>>shift)&MASK; var newNode; var nodes=idx1===idx2? [mergeIntoNode(node,ownerID,shift+SHIFT,keyHash,entry)]:( newNode=new ValueNode(ownerID,keyHash,entry),idx1>>=1){ expandedNodes[ii]=bitmap&1?nodes[count++]:undefined;} expandedNodes[including]=node; return new HashArrayMapNode(ownerID,count+1,expandedNodes);} function mergeIntoMapWith(map,merger,iterables){ var iters=[]; for(var ii=0;ii>1&0x55555555); x=(x&0x33333333)+(x>>2&0x33333333); x=x+(x>>4)&0x0f0f0f0f; x=x+(x>>8); x=x+(x>>16); return x&0x7f;} function setIn(array,idx,val,canEdit){ var newArray=canEdit?array:arrCopy(array); newArray[idx]=val; return newArray;} function spliceIn(array,idx,val,canEdit){ var newLen=array.length+1; if(canEdit&&idx+1===newLen){ array[idx]=val; return array;} var newArray=new Array(newLen); var after=0; for(var ii=0;ii0&&size=0&&index>>level&MASK; if(originIndex>=this.array.length){ return new VNode([],ownerID);} var removingFirst=originIndex===0; var newChild; if(level>0){ var oldChild=this.array[originIndex]; newChild=oldChild&&oldChild.removeBefore(ownerID,level-SHIFT,index); if(newChild===oldChild&&removingFirst){ return this;}} if(removingFirst&&!newChild){ return this;} var editable=editableVNode(this,ownerID); if(!removingFirst){ for(var ii=0;ii>>level&MASK; if(sizeIndex>=this.array.length){ return this;} var newChild; if(level>0){ var oldChild=this.array[sizeIndex]; newChild=oldChild&&oldChild.removeAfter(ownerID,level-SHIFT,index); if(newChild===oldChild&&sizeIndex===this.array.length-1){ return this;}} var editable=editableVNode(this,ownerID); editable.array.splice(sizeIndex+1); if(newChild){ editable.array[sizeIndex]=newChild;} return editable;}; var DONE={}; function iterateList(list,reverse){ var left=list._origin; var right=list._capacity; var tailPos=getTailOffset(right); var tail=list._tail; return iterateNodeOrLeaf(list._root,list._level,0); function iterateNodeOrLeaf(node,level,offset){ return level===0? iterateLeaf(node,offset): iterateNode(node,level,offset);} function iterateLeaf(node,offset){ var array=offset===tailPos?tail&&tail.array:node&&node.array; var from=offset>left?0:left-offset; var to=right-offset; if(to>SIZE){ to=SIZE;} return function(){ if(from===to){ return DONE;} var idx=reverse?--to:from++; return array&&array[idx];};} function iterateNode(node,level,offset){ var values; var array=node&&node.array; var from=offset>left?0:left-offset>>level; var to=(right-offset>>level)+1; if(to>SIZE){ to=SIZE;} return function(){ do { if(values){ var value=values(); if(value!==DONE){ return value;} values=null;} if(from===to){ return DONE;} var idx=reverse?--to:from++; values=iterateNodeOrLeaf( array&&array[idx],level-SHIFT,offset+(idx<=list.size||index<0){ return list.withMutations(function(list){ index<0? setListBounds(list,index).set(0,value): setListBounds(list,0,index+1).set(index,value);});} index+=list._origin; var newTail=list._tail; var newRoot=list._root; var didAlter=MakeRef(DID_ALTER); if(index>=getTailOffset(list._capacity)){ newTail=updateVNode(newTail,list.__ownerID,0,index,value,didAlter);}else { newRoot=updateVNode(newRoot,list.__ownerID,list._level,index,value,didAlter);} if(!didAlter.value){ return list;} if(list.__ownerID){ list._root=newRoot; list._tail=newTail; list.__hash=undefined; list.__altered=true; return list;} return makeList(list._origin,list._capacity,list._level,newRoot,newTail);} function updateVNode(node,ownerID,level,index,value,didAlter){ var idx=index>>>level&MASK; var nodeHas=node&&idx0){ var lowerNode=node&&node.array[idx]; var newLowerNode=updateVNode(lowerNode,ownerID,level-SHIFT,index,value,didAlter); if(newLowerNode===lowerNode){ return node;} newNode=editableVNode(node,ownerID); newNode.array[idx]=newLowerNode; return newNode;} if(nodeHas&&node.array[idx]===value){ return node;} SetRef(didAlter); newNode=editableVNode(node,ownerID); if(value===undefined&&idx===newNode.array.length-1){ newNode.array.pop();}else { newNode.array[idx]=value;} return newNode;} function editableVNode(node,ownerID){ if(ownerID&&node&&ownerID===node.ownerID){ return node;} return new VNode(node?node.array.slice():[],ownerID);} function listNodeFor(list,rawIndex){ if(rawIndex>=getTailOffset(list._capacity)){ return list._tail;} if(rawIndex<1<0){ node=node.array[rawIndex>>>level&MASK]; level-=SHIFT;} return node;}} function setListBounds(list,begin,end){ if(begin!==undefined){ begin=begin|0;} if(end!==undefined){ end=end|0;} var owner=list.__ownerID||new OwnerID(); var oldOrigin=list._origin; var oldCapacity=list._capacity; var newOrigin=oldOrigin+begin; var newCapacity=end===undefined?oldCapacity:end<0?oldCapacity+end:oldOrigin+end; if(newOrigin===oldOrigin&&newCapacity===oldCapacity){ return list;} if(newOrigin>=newCapacity){ return list.clear();} var newLevel=list._level; var newRoot=list._root; var offsetShift=0; while(newOrigin+offsetShift<0){ newRoot=new VNode(newRoot&&newRoot.array.length?[undefined,newRoot]:[],owner); newLevel+=SHIFT; offsetShift+=1<=1<oldTailOffset?new VNode([],owner):oldTail; if(oldTail&&newTailOffset>oldTailOffset&&newOriginSHIFT;level-=SHIFT){ var idx=oldTailOffset>>>level&MASK; node=node.array[idx]=editableVNode(node.array[idx],owner);} node.array[oldTailOffset>>>SHIFT&MASK]=oldTail;} if(newCapacity=newTailOffset){ newOrigin-=newTailOffset; newCapacity-=newTailOffset; newLevel=SHIFT; newRoot=null; newTail=newTail&&newTail.removeBefore(owner,0,newOrigin);}else if(newOrigin>oldOrigin||newTailOffset>>newLevel&MASK; if(beginIndex!==newTailOffset>>>newLevel&MASK){ break;} if(beginIndex){ offsetShift+=(1<oldOrigin){ newRoot=newRoot.removeBefore(owner,newLevel,newOrigin-offsetShift);} if(newRoot&&newTailOffsetmaxSize){ maxSize=iter.size;} if(!isIterable(value)){ iter=iter.map(function(v){return fromJS(v);});} iters.push(iter);} if(maxSize>list.size){ list=list.setSize(maxSize);} return mergeIntoCollectionWith(list,merger,iters);} function getTailOffset(size){ return size>>SHIFT<=SIZE&&list.size>=map.size*2){ newList=list.filter(function(entry,idx){return entry!==undefined&&i!==idx;}); newMap=newList.toKeyedSeq().map(function(entry){return entry[0];}).flip().toMap(); if(omap.__ownerID){ newMap.__ownerID=newList.__ownerID=omap.__ownerID;}}else { newMap=map.remove(k); newList=i===list.size-1?list.pop():list.set(i,undefined);}}else { if(has){ if(v===list.get(i)[1]){ return omap;} newMap=map; newList=list.set(i,[k,v]);}else { newMap=map.set(k,list.size); newList=list.set(list.size,[k,v]);}} if(omap.__ownerID){ omap.size=newMap.size; omap._map=newMap; omap._list=newList; omap.__hash=undefined; return omap;} return makeOrderedMap(newMap,newList);} createClass(ToKeyedSequence,KeyedSeq); function ToKeyedSequence(indexed,useKeys){ this._iter=indexed; this._useKeys=useKeys; this.size=indexed.size;} ToKeyedSequence.prototype.get=function(key,notSetValue){ return this._iter.get(key,notSetValue);}; ToKeyedSequence.prototype.has=function(key){ return this._iter.has(key);}; ToKeyedSequence.prototype.valueSeq=function(){ return this._iter.valueSeq();}; ToKeyedSequence.prototype.reverse=function(){var this$0=this; var reversedSequence=reverseFactory(this,true); if(!this._useKeys){ reversedSequence.valueSeq=function(){return this$0._iter.toSeq().reverse();};} return reversedSequence;}; ToKeyedSequence.prototype.map=function(mapper,context){var this$0=this; var mappedSequence=mapFactory(this,mapper,context); if(!this._useKeys){ mappedSequence.valueSeq=function(){return this$0._iter.toSeq().map(mapper,context);};} return mappedSequence;}; ToKeyedSequence.prototype.__iterate=function(fn,reverse){var this$0=this; var ii; return this._iter.__iterate( this._useKeys? function(v,k){return fn(v,k,this$0);}:( ii=reverse?resolveSize(this):0, function(v){return fn(v,reverse?--ii:ii++,this$0);}), reverse);}; ToKeyedSequence.prototype.__iterator=function(type,reverse){ if(this._useKeys){ return this._iter.__iterator(type,reverse);} var iterator=this._iter.__iterator(ITERATE_VALUES,reverse); var ii=reverse?resolveSize(this):0; return new Iterator(function(){ var step=iterator.next(); return step.done?step: iteratorValue(type,reverse?--ii:ii++,step.value,step);});}; ToKeyedSequence.prototype[IS_ORDERED_SENTINEL]=true; createClass(ToIndexedSequence,IndexedSeq); function ToIndexedSequence(iter){ this._iter=iter; this.size=iter.size;} ToIndexedSequence.prototype.includes=function(value){ return this._iter.includes(value);}; ToIndexedSequence.prototype.__iterate=function(fn,reverse){var this$0=this; var iterations=0; return this._iter.__iterate(function(v){return fn(v,iterations++,this$0);},reverse);}; ToIndexedSequence.prototype.__iterator=function(type,reverse){ var iterator=this._iter.__iterator(ITERATE_VALUES,reverse); var iterations=0; return new Iterator(function(){ var step=iterator.next(); return step.done?step: iteratorValue(type,iterations++,step.value,step);});}; createClass(ToSetSequence,SetSeq); function ToSetSequence(iter){ this._iter=iter; this.size=iter.size;} ToSetSequence.prototype.has=function(key){ return this._iter.includes(key);}; ToSetSequence.prototype.__iterate=function(fn,reverse){var this$0=this; return this._iter.__iterate(function(v){return fn(v,v,this$0);},reverse);}; ToSetSequence.prototype.__iterator=function(type,reverse){ var iterator=this._iter.__iterator(ITERATE_VALUES,reverse); return new Iterator(function(){ var step=iterator.next(); return step.done?step: iteratorValue(type,step.value,step.value,step);});}; createClass(FromEntriesSequence,KeyedSeq); function FromEntriesSequence(entries){ this._iter=entries; this.size=entries.size;} FromEntriesSequence.prototype.entrySeq=function(){ return this._iter.toSeq();}; FromEntriesSequence.prototype.__iterate=function(fn,reverse){var this$0=this; return this._iter.__iterate(function(entry){ if(entry){ validateEntry(entry); var indexedIterable=isIterable(entry); return fn( indexedIterable?entry.get(1):entry[1], indexedIterable?entry.get(0):entry[0], this$0);}}, reverse);}; FromEntriesSequence.prototype.__iterator=function(type,reverse){ var iterator=this._iter.__iterator(ITERATE_VALUES,reverse); return new Iterator(function(){ while(true){ var step=iterator.next(); if(step.done){ return step;} var entry=step.value; if(entry){ validateEntry(entry); var indexedIterable=isIterable(entry); return iteratorValue( type, indexedIterable?entry.get(0):entry[0], indexedIterable?entry.get(1):entry[1], step);}}});}; ToIndexedSequence.prototype.cacheResult= ToKeyedSequence.prototype.cacheResult= ToSetSequence.prototype.cacheResult= FromEntriesSequence.prototype.cacheResult= cacheResultThrough; function flipFactory(iterable){ var flipSequence=makeSequence(iterable); flipSequence._iter=iterable; flipSequence.size=iterable.size; flipSequence.flip=function(){return iterable;}; flipSequence.reverse=function(){ var reversedSequence=iterable.reverse.apply(this); reversedSequence.flip=function(){return iterable.reverse();}; return reversedSequence;}; flipSequence.has=function(key){return iterable.includes(key);}; flipSequence.includes=function(key){return iterable.has(key);}; flipSequence.cacheResult=cacheResultThrough; flipSequence.__iterateUncached=function(fn,reverse){var this$0=this; return iterable.__iterate(function(v,k){return fn(k,v,this$0)!==false;},reverse);}; flipSequence.__iteratorUncached=function(type,reverse){ if(type===ITERATE_ENTRIES){ var iterator=iterable.__iterator(type,reverse); return new Iterator(function(){ var step=iterator.next(); if(!step.done){ var k=step.value[0]; step.value[0]=step.value[1]; step.value[1]=k;} return step;});} return iterable.__iterator( type===ITERATE_VALUES?ITERATE_KEYS:ITERATE_VALUES, reverse);}; return flipSequence;} function mapFactory(iterable,mapper,context){ var mappedSequence=makeSequence(iterable); mappedSequence.size=iterable.size; mappedSequence.has=function(key){return iterable.has(key);}; mappedSequence.get=function(key,notSetValue){ var v=iterable.get(key,NOT_SET); return v===NOT_SET? notSetValue: mapper.call(context,v,key,iterable);}; mappedSequence.__iterateUncached=function(fn,reverse){var this$0=this; return iterable.__iterate( function(v,k,c){return fn(mapper.call(context,v,k,c),k,this$0)!==false;}, reverse);}; mappedSequence.__iteratorUncached=function(type,reverse){ var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse); return new Iterator(function(){ var step=iterator.next(); if(step.done){ return step;} var entry=step.value; var key=entry[0]; return iteratorValue( type, key, mapper.call(context,entry[1],key,iterable), step);});}; return mappedSequence;} function reverseFactory(iterable,useKeys){ var reversedSequence=makeSequence(iterable); reversedSequence._iter=iterable; reversedSequence.size=iterable.size; reversedSequence.reverse=function(){return iterable;}; if(iterable.flip){ reversedSequence.flip=function(){ var flipSequence=flipFactory(iterable); flipSequence.reverse=function(){return iterable.flip();}; return flipSequence;};} reversedSequence.get=function(key,notSetValue) {return iterable.get(useKeys?key:-1-key,notSetValue);}; reversedSequence.has=function(key) {return iterable.has(useKeys?key:-1-key);}; reversedSequence.includes=function(value){return iterable.includes(value);}; reversedSequence.cacheResult=cacheResultThrough; reversedSequence.__iterate=function(fn,reverse){var this$0=this; return iterable.__iterate(function(v,k){return fn(v,k,this$0);},!reverse);}; reversedSequence.__iterator= function(type,reverse){return iterable.__iterator(type,!reverse);}; return reversedSequence;} function filterFactory(iterable,predicate,context,useKeys){ var filterSequence=makeSequence(iterable); if(useKeys){ filterSequence.has=function(key){ var v=iterable.get(key,NOT_SET); return v!==NOT_SET&&!!predicate.call(context,v,key,iterable);}; filterSequence.get=function(key,notSetValue){ var v=iterable.get(key,NOT_SET); return v!==NOT_SET&&predicate.call(context,v,key,iterable)? v:notSetValue;};} filterSequence.__iterateUncached=function(fn,reverse){var this$0=this; var iterations=0; iterable.__iterate(function(v,k,c){ if(predicate.call(context,v,k,c)){ iterations++; return fn(v,useKeys?k:iterations-1,this$0);}}, reverse); return iterations;}; filterSequence.__iteratorUncached=function(type,reverse){ var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse); var iterations=0; return new Iterator(function(){ while(true){ var step=iterator.next(); if(step.done){ return step;} var entry=step.value; var key=entry[0]; var value=entry[1]; if(predicate.call(context,value,key,iterable)){ return iteratorValue(type,useKeys?key:iterations++,value,step);}}});}; return filterSequence;} function countByFactory(iterable,grouper,context){ var groups=Map().asMutable(); iterable.__iterate(function(v,k){ groups.update( grouper.call(context,v,k,iterable), 0, function(a){return a+1;});}); return groups.asImmutable();} function groupByFactory(iterable,grouper,context){ var isKeyedIter=isKeyed(iterable); var groups=(isOrdered(iterable)?OrderedMap():Map()).asMutable(); iterable.__iterate(function(v,k){ groups.update( grouper.call(context,v,k,iterable), function(a){return a=a||[],a.push(isKeyedIter?[k,v]:v),a;});}); var coerce=iterableClass(iterable); return groups.map(function(arr){return reify(iterable,coerce(arr));});} function sliceFactory(iterable,begin,end,useKeys){ var originalSize=iterable.size; if(begin!==undefined){ begin=begin|0;} if(end!==undefined){ end=end|0;} if(wholeSlice(begin,end,originalSize)){ return iterable;} var resolvedBegin=resolveBegin(begin,originalSize); var resolvedEnd=resolveEnd(end,originalSize); if(resolvedBegin!==resolvedBegin||resolvedEnd!==resolvedEnd){ return sliceFactory(iterable.toSeq().cacheResult(),begin,end,useKeys);} var resolvedSize=resolvedEnd-resolvedBegin; var sliceSize; if(resolvedSize===resolvedSize){ sliceSize=resolvedSize<0?0:resolvedSize;} var sliceSeq=makeSequence(iterable); sliceSeq.size=sliceSize===0?sliceSize:iterable.size&&sliceSize||undefined; if(!useKeys&&isSeq(iterable)&&sliceSize>=0){ sliceSeq.get=function(index,notSetValue){ index=wrapIndex(this,index); return index>=0&&indexsliceSize){ return iteratorDone();} var step=iterator.next(); if(useKeys||type===ITERATE_VALUES){ return step;}else if(type===ITERATE_KEYS){ return iteratorValue(type,iterations-1,undefined,step);}else { return iteratorValue(type,iterations-1,step.value[1],step);}});}; return sliceSeq;} function takeWhileFactory(iterable,predicate,context){ var takeSequence=makeSequence(iterable); takeSequence.__iterateUncached=function(fn,reverse){var this$0=this; if(reverse){ return this.cacheResult().__iterate(fn,reverse);} var iterations=0; iterable.__iterate(function(v,k,c) {return predicate.call(context,v,k,c)&&++iterations&&fn(v,k,this$0);}); return iterations;}; takeSequence.__iteratorUncached=function(type,reverse){var this$0=this; if(reverse){ return this.cacheResult().__iterator(type,reverse);} var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse); var iterating=true; return new Iterator(function(){ if(!iterating){ return iteratorDone();} var step=iterator.next(); if(step.done){ return step;} var entry=step.value; var k=entry[0]; var v=entry[1]; if(!predicate.call(context,v,k,this$0)){ iterating=false; return iteratorDone();} return type===ITERATE_ENTRIES?step: iteratorValue(type,k,v,step);});}; return takeSequence;} function skipWhileFactory(iterable,predicate,context,useKeys){ var skipSequence=makeSequence(iterable); skipSequence.__iterateUncached=function(fn,reverse){var this$0=this; if(reverse){ return this.cacheResult().__iterate(fn,reverse);} var isSkipping=true; var iterations=0; iterable.__iterate(function(v,k,c){ if(!(isSkipping&&(isSkipping=predicate.call(context,v,k,c)))){ iterations++; return fn(v,useKeys?k:iterations-1,this$0);}}); return iterations;}; skipSequence.__iteratorUncached=function(type,reverse){var this$0=this; if(reverse){ return this.cacheResult().__iterator(type,reverse);} var iterator=iterable.__iterator(ITERATE_ENTRIES,reverse); var skipping=true; var iterations=0; return new Iterator(function(){ var step,k,v; do { step=iterator.next(); if(step.done){ if(useKeys||type===ITERATE_VALUES){ return step;}else if(type===ITERATE_KEYS){ return iteratorValue(type,iterations++,undefined,step);}else { return iteratorValue(type,iterations++,step.value[1],step);}} var entry=step.value; k=entry[0]; v=entry[1]; skipping&&(skipping=predicate.call(context,v,k,this$0));}while( skipping); return type===ITERATE_ENTRIES?step: iteratorValue(type,k,v,step);});}; return skipSequence;} function concatFactory(iterable,values){ var isKeyedIterable=isKeyed(iterable); var iters=[iterable].concat(values).map(function(v){ if(!isIterable(v)){ v=isKeyedIterable? keyedSeqFromValue(v): indexedSeqFromValue(Array.isArray(v)?v:[v]);}else if(isKeyedIterable){ v=KeyedIterable(v);} return v;}). filter(function(v){return v.size!==0;}); if(iters.length===0){ return iterable;} if(iters.length===1){ var singleton=iters[0]; if(singleton===iterable|| isKeyedIterable&&isKeyed(singleton)|| isIndexed(iterable)&&isIndexed(singleton)){ return singleton;}} var concatSeq=new ArraySeq(iters); if(isKeyedIterable){ concatSeq=concatSeq.toKeyedSeq();}else if(!isIndexed(iterable)){ concatSeq=concatSeq.toSetSeq();} concatSeq=concatSeq.flatten(true); concatSeq.size=iters.reduce( function(sum,seq){ if(sum!==undefined){ var size=seq.size; if(size!==undefined){ return sum+size;}}}, 0); return concatSeq;} function flattenFactory(iterable,depth,useKeys){ var flatSequence=makeSequence(iterable); flatSequence.__iterateUncached=function(fn,reverse){ var iterations=0; var stopped=false; function flatDeep(iter,currentDepth){var this$0=this; iter.__iterate(function(v,k){ if((!depth||currentDepth0;} function zipWithFactory(keyIter,zipper,iters){ var zipSequence=makeSequence(keyIter); zipSequence.size=new ArraySeq(iters).map(function(i){return i.size;}).min(); zipSequence.__iterate=function(fn,reverse){ var iterator=this.__iterator(ITERATE_VALUES,reverse); var step; var iterations=0; while(!(step=iterator.next()).done){ if(fn(step.value,iterations++,this)===false){ break;}} return iterations;}; zipSequence.__iteratorUncached=function(type,reverse){ var iterators=iters.map(function(i) {return i=Iterable(i),getIterator(reverse?i.reverse():i);}); var iterations=0; var isDone=false; return new Iterator(function(){ var steps; if(!isDone){ steps=iterators.map(function(i){return i.next();}); isDone=steps.some(function(s){return s.done;});} if(isDone){ return iteratorDone();} return iteratorValue( type, iterations++, zipper.apply(null,steps.map(function(s){return s.value;})));});}; return zipSequence;} function reify(iter,seq){ return isSeq(iter)?seq:iter.constructor(seq);} function validateEntry(entry){ if(entry!==Object(entry)){ throw new TypeError('Expected [K, V] tuple: '+entry);}} function resolveSize(iter){ assertNotInfinite(iter.size); return ensureSize(iter);} function iterableClass(iterable){ return isKeyed(iterable)?KeyedIterable: isIndexed(iterable)?IndexedIterable: SetIterable;} function makeSequence(iterable){ return Object.create( ( isKeyed(iterable)?KeyedSeq: isIndexed(iterable)?IndexedSeq: SetSeq). prototype);} function cacheResultThrough(){ if(this._iter.cacheResult){ this._iter.cacheResult(); this.size=this._iter.size; return this;}else { return Seq.prototype.cacheResult.call(this);}} function defaultComparator(a,b){ return a>b?1:a=0;ii--){ head={ value:arguments[ii], next:head};} if(this.__ownerID){ this.size=newSize; this._head=head; this.__hash=undefined; this.__altered=true; return this;} return makeStack(newSize,head);}; Stack.prototype.pushAll=function(iter){ iter=IndexedIterable(iter); if(iter.size===0){ return this;} assertNotInfinite(iter.size); var newSize=this.size; var head=this._head; iter.reverse().forEach(function(value){ newSize++; head={ value:value, next:head};}); if(this.__ownerID){ this.size=newSize; this._head=head; this.__hash=undefined; this.__altered=true; return this;} return makeStack(newSize,head);}; Stack.prototype.pop=function(){ return this.slice(1);}; Stack.prototype.unshift=function(){ return this.push.apply(this,arguments);}; Stack.prototype.unshiftAll=function(iter){ return this.pushAll(iter);}; Stack.prototype.shift=function(){ return this.pop.apply(this,arguments);}; Stack.prototype.clear=function(){ if(this.size===0){ return this;} if(this.__ownerID){ this.size=0; this._head=undefined; this.__hash=undefined; this.__altered=true; return this;} return emptyStack();}; Stack.prototype.slice=function(begin,end){ if(wholeSlice(begin,end,this.size)){ return this;} var resolvedBegin=resolveBegin(begin,this.size); var resolvedEnd=resolveEnd(end,this.size); if(resolvedEnd!==this.size){ return IndexedCollection.prototype.slice.call(this,begin,end);} var newSize=this.size-resolvedBegin; var head=this._head; while(resolvedBegin--){ head=head.next;} if(this.__ownerID){ this.size=newSize; this._head=head; this.__hash=undefined; this.__altered=true; return this;} return makeStack(newSize,head);}; Stack.prototype.__ensureOwner=function(ownerID){ if(ownerID===this.__ownerID){ return this;} if(!ownerID){ this.__ownerID=ownerID; this.__altered=false; return this;} return makeStack(this.size,this._head,ownerID,this.__hash);}; Stack.prototype.__iterate=function(fn,reverse){ if(reverse){ return this.reverse().__iterate(fn);} var iterations=0; var node=this._head; while(node){ if(fn(node.value,iterations++,this)===false){ break;} node=node.next;} return iterations;}; Stack.prototype.__iterator=function(type,reverse){ if(reverse){ return this.reverse().__iterator(type);} var iterations=0; var node=this._head; return new Iterator(function(){ if(node){ var value=node.value; node=node.next; return iteratorValue(type,iterations++,value);} return iteratorDone();});}; function isStack(maybeStack){ return !!(maybeStack&&maybeStack[IS_STACK_SENTINEL]);} Stack.isStack=isStack; var IS_STACK_SENTINEL='@@__IMMUTABLE_STACK__@@'; var StackPrototype=Stack.prototype; StackPrototype[IS_STACK_SENTINEL]=true; StackPrototype.withMutations=MapPrototype.withMutations; StackPrototype.asMutable=MapPrototype.asMutable; StackPrototype.asImmutable=MapPrototype.asImmutable; StackPrototype.wasAltered=MapPrototype.wasAltered; function makeStack(size,head,ownerID,hash){ var map=Object.create(StackPrototype); map.size=size; map._head=head; map.__ownerID=ownerID; map.__hash=hash; map.__altered=false; return map;} var EMPTY_STACK; function emptyStack(){ return EMPTY_STACK||(EMPTY_STACK=makeStack(0));} function mixin(ctor,methods){ var keyCopier=function(key){ctor.prototype[key]=methods[key];}; Object.keys(methods).forEach(keyCopier); Object.getOwnPropertySymbols&& Object.getOwnPropertySymbols(methods).forEach(keyCopier); return ctor;} Iterable.Iterator=Iterator; mixin(Iterable,{ toArray:function(){ assertNotInfinite(this.size); var array=new Array(this.size||0); this.valueSeq().__iterate(function(v,i){array[i]=v;}); return array;}, toIndexedSeq:function(){ return new ToIndexedSequence(this);}, toJS:function(){ return this.toSeq().map( function(value){return value&&typeof value.toJS==='function'?value.toJS():value;}). __toJS();}, toJSON:function(){ return this.toSeq().map( function(value){return value&&typeof value.toJSON==='function'?value.toJSON():value;}). __toJS();}, toKeyedSeq:function(){ return new ToKeyedSequence(this,true);}, toMap:function(){ return Map(this.toKeyedSeq());}, toObject:function(){ assertNotInfinite(this.size); var object={}; this.__iterate(function(v,k){object[k]=v;}); return object;}, toOrderedMap:function(){ return OrderedMap(this.toKeyedSeq());}, toOrderedSet:function(){ return OrderedSet(isKeyed(this)?this.valueSeq():this);}, toSet:function(){ return Set(isKeyed(this)?this.valueSeq():this);}, toSetSeq:function(){ return new ToSetSequence(this);}, toSeq:function(){ return isIndexed(this)?this.toIndexedSeq(): isKeyed(this)?this.toKeyedSeq(): this.toSetSeq();}, toStack:function(){ return Stack(isKeyed(this)?this.valueSeq():this);}, toList:function(){ return List(isKeyed(this)?this.valueSeq():this);}, toString:function(){ return '[Iterable]';}, __toString:function(head,tail){ if(this.size===0){ return head+tail;} return head+' '+this.toSeq().map(this.__toStringMapper).join(', ')+' '+tail;}, concat:function(){var values=SLICE$0.call(arguments,0); return reify(this,concatFactory(this,values));}, includes:function(searchValue){ return this.some(function(value){return is(value,searchValue);});}, entries:function(){ return this.__iterator(ITERATE_ENTRIES);}, every:function(predicate,context){ assertNotInfinite(this.size); var returnValue=true; this.__iterate(function(v,k,c){ if(!predicate.call(context,v,k,c)){ returnValue=false; return false;}}); return returnValue;}, filter:function(predicate,context){ return reify(this,filterFactory(this,predicate,context,true));}, find:function(predicate,context,notSetValue){ var entry=this.findEntry(predicate,context); return entry?entry[1]:notSetValue;}, findEntry:function(predicate,context){ var found; this.__iterate(function(v,k,c){ if(predicate.call(context,v,k,c)){ found=[k,v]; return false;}}); return found;}, findLastEntry:function(predicate,context){ return this.toSeq().reverse().findEntry(predicate,context);}, forEach:function(sideEffect,context){ assertNotInfinite(this.size); return this.__iterate(context?sideEffect.bind(context):sideEffect);}, join:function(separator){ assertNotInfinite(this.size); separator=separator!==undefined?''+separator:','; var joined=''; var isFirst=true; this.__iterate(function(v){ isFirst?isFirst=false:joined+=separator; joined+=v!==null&&v!==undefined?v.toString():'';}); return joined;}, keys:function(){ return this.__iterator(ITERATE_KEYS);}, map:function(mapper,context){ return reify(this,mapFactory(this,mapper,context));}, reduce:function(reducer,initialReduction,context){ assertNotInfinite(this.size); var reduction; var useFirst; if(arguments.length<2){ useFirst=true;}else { reduction=initialReduction;} this.__iterate(function(v,k,c){ if(useFirst){ useFirst=false; reduction=v;}else { reduction=reducer.call(context,reduction,v,k,c);}}); return reduction;}, reduceRight:function(reducer,initialReduction,context){ var reversed=this.toKeyedSeq().reverse(); return reversed.reduce.apply(reversed,arguments);}, reverse:function(){ return reify(this,reverseFactory(this,true));}, slice:function(begin,end){ return reify(this,sliceFactory(this,begin,end,true));}, some:function(predicate,context){ return !this.every(not(predicate),context);}, sort:function(comparator){ return reify(this,sortFactory(this,comparator));}, values:function(){ return this.__iterator(ITERATE_VALUES);}, butLast:function(){ return this.slice(0,-1);}, isEmpty:function(){ return this.size!==undefined?this.size===0:!this.some(function(){return true;});}, count:function(predicate,context){ return ensureSize( predicate?this.toSeq().filter(predicate,context):this);}, countBy:function(grouper,context){ return countByFactory(this,grouper,context);}, equals:function(other){ return deepEqual(this,other);}, entrySeq:function(){ var iterable=this; if(iterable._cache){ return new ArraySeq(iterable._cache);} var entriesSequence=iterable.toSeq().map(entryMapper).toIndexedSeq(); entriesSequence.fromEntrySeq=function(){return iterable.toSeq();}; return entriesSequence;}, filterNot:function(predicate,context){ return this.filter(not(predicate),context);}, findLast:function(predicate,context,notSetValue){ return this.toKeyedSeq().reverse().find(predicate,context,notSetValue);}, first:function(){ return this.find(returnTrue);}, flatMap:function(mapper,context){ return reify(this,flatMapFactory(this,mapper,context));}, flatten:function(depth){ return reify(this,flattenFactory(this,depth,true));}, fromEntrySeq:function(){ return new FromEntriesSequence(this);}, get:function(searchKey,notSetValue){ return this.find(function(_,key){return is(key,searchKey);},undefined,notSetValue);}, getIn:function(searchKeyPath,notSetValue){ var nested=this; var iter=forceIterator(searchKeyPath); var step; while(!(step=iter.next()).done){ var key=step.value; nested=nested&&nested.get?nested.get(key,NOT_SET):NOT_SET; if(nested===NOT_SET){ return notSetValue;}} return nested;}, groupBy:function(grouper,context){ return groupByFactory(this,grouper,context);}, has:function(searchKey){ return this.get(searchKey,NOT_SET)!==NOT_SET;}, hasIn:function(searchKeyPath){ return this.getIn(searchKeyPath,NOT_SET)!==NOT_SET;}, isSubset:function(iter){ iter=typeof iter.includes==='function'?iter:Iterable(iter); return this.every(function(value){return iter.includes(value);});}, isSuperset:function(iter){ iter=typeof iter.isSubset==='function'?iter:Iterable(iter); return iter.isSubset(this);}, keySeq:function(){ return this.toSeq().map(keyMapper).toIndexedSeq();}, last:function(){ return this.toSeq().reverse().first();}, max:function(comparator){ return maxFactory(this,comparator);}, maxBy:function(mapper,comparator){ return maxFactory(this,comparator,mapper);}, min:function(comparator){ return maxFactory(this,comparator?neg(comparator):defaultNegComparator);}, minBy:function(mapper,comparator){ return maxFactory(this,comparator?neg(comparator):defaultNegComparator,mapper);}, rest:function(){ return this.slice(1);}, skip:function(amount){ return this.slice(Math.max(0,amount));}, skipLast:function(amount){ return reify(this,this.toSeq().reverse().skip(amount).reverse());}, skipWhile:function(predicate,context){ return reify(this,skipWhileFactory(this,predicate,context,true));}, skipUntil:function(predicate,context){ return this.skipWhile(not(predicate),context);}, sortBy:function(mapper,comparator){ return reify(this,sortFactory(this,comparator,mapper));}, take:function(amount){ return this.slice(0,Math.max(0,amount));}, takeLast:function(amount){ return reify(this,this.toSeq().reverse().take(amount).reverse());}, takeWhile:function(predicate,context){ return reify(this,takeWhileFactory(this,predicate,context));}, takeUntil:function(predicate,context){ return this.takeWhile(not(predicate),context);}, valueSeq:function(){ return this.toIndexedSeq();}, hashCode:function(){ return this.__hash||(this.__hash=hashIterable(this));}}); var IterablePrototype=Iterable.prototype; IterablePrototype[IS_ITERABLE_SENTINEL]=true; IterablePrototype[ITERATOR_SYMBOL]=IterablePrototype.values; IterablePrototype.__toJS=IterablePrototype.toArray; IterablePrototype.__toStringMapper=quoteString; IterablePrototype.inspect= IterablePrototype.toSource=function(){return this.toString();}; IterablePrototype.chain=IterablePrototype.flatMap; IterablePrototype.contains=IterablePrototype.includes; (function(){ try{ Object.defineProperty(IterablePrototype,'length',{ get:function(){ if(!Iterable.noLengthWarning){ var stack; try{ throw new Error();} catch(error) { stack=error.stack;} if(stack.indexOf('_wrapObject')===-1){ console&&console.warn&&console.warn( 'iterable.length has been deprecated, '+ 'use iterable.size or iterable.count(). '+ 'This warning will become a silent error in a future version. '+ stack); return this.size;}}}});} catch(e) {}})(); mixin(KeyedIterable,{ flip:function(){ return reify(this,flipFactory(this));}, findKey:function(predicate,context){ var entry=this.findEntry(predicate,context); return entry&&entry[0];}, findLastKey:function(predicate,context){ return this.toSeq().reverse().findKey(predicate,context);}, keyOf:function(searchValue){ return this.findKey(function(value){return is(value,searchValue);});}, lastKeyOf:function(searchValue){ return this.findLastKey(function(value){return is(value,searchValue);});}, mapEntries:function(mapper,context){var this$0=this; var iterations=0; return reify(this, this.toSeq().map( function(v,k){return mapper.call(context,[k,v],iterations++,this$0);}). fromEntrySeq());}, mapKeys:function(mapper,context){var this$0=this; return reify(this, this.toSeq().flip().map( function(k,v){return mapper.call(context,k,v,this$0);}). flip());}}); var KeyedIterablePrototype=KeyedIterable.prototype; KeyedIterablePrototype[IS_KEYED_SENTINEL]=true; KeyedIterablePrototype[ITERATOR_SYMBOL]=IterablePrototype.entries; KeyedIterablePrototype.__toJS=IterablePrototype.toObject; KeyedIterablePrototype.__toStringMapper=function(v,k){return JSON.stringify(k)+': '+quoteString(v);}; mixin(IndexedIterable,{ toKeyedSeq:function(){ return new ToKeyedSequence(this,false);}, filter:function(predicate,context){ return reify(this,filterFactory(this,predicate,context,false));}, findIndex:function(predicate,context){ var entry=this.findEntry(predicate,context); return entry?entry[0]:-1;}, indexOf:function(searchValue){ var key=this.toKeyedSeq().keyOf(searchValue); return key===undefined?-1:key;}, lastIndexOf:function(searchValue){ var key=this.toKeyedSeq().reverse().keyOf(searchValue); return key===undefined?-1:key;}, reverse:function(){ return reify(this,reverseFactory(this,false));}, slice:function(begin,end){ return reify(this,sliceFactory(this,begin,end,false));}, splice:function(index,removeNum){ var numArgs=arguments.length; removeNum=Math.max(removeNum|0,0); if(numArgs===0||numArgs===2&&!removeNum){ return this;} index=resolveBegin(index,index<0?this.count():this.size); var spliced=this.slice(0,index); return reify( this, numArgs===1? spliced: spliced.concat(arrCopy(arguments,2),this.slice(index+removeNum)));}, findLastIndex:function(predicate,context){ var key=this.toKeyedSeq().findLastKey(predicate,context); return key===undefined?-1:key;}, first:function(){ return this.get(0);}, flatten:function(depth){ return reify(this,flattenFactory(this,depth,false));}, get:function(index,notSetValue){ index=wrapIndex(this,index); return index<0||this.size===Infinity|| this.size!==undefined&&index>this.size? notSetValue: this.find(function(_,key){return key===index;},undefined,notSetValue);}, has:function(index){ index=wrapIndex(this,index); return index>=0&&(this.size!==undefined? this.size===Infinity||indexb?-1:0;} function hashIterable(iterable){ if(iterable.size===Infinity){ return 0;} var ordered=isOrdered(iterable); var keyed=isKeyed(iterable); var h=ordered?1:0; var size=iterable.__iterate( keyed? ordered? function(v,k){h=31*h+hashMerge(hash(v),hash(k))|0;}: function(v,k){h=h+hashMerge(hash(v),hash(k))|0;}: ordered? function(v){h=31*h+hash(v)|0;}: function(v){h=h+hash(v)|0;}); return murmurHashOfSize(size,h);} function murmurHashOfSize(size,h){ h=imul(h,0xCC9E2D51); h=imul(h<<15|h>>>-15,0x1B873593); h=imul(h<<13|h>>>-13,5); h=(h+0xE6546B64|0)^size; h=imul(h^h>>>16,0x85EBCA6B); h=imul(h^h>>>13,0xC2B2AE35); h=smi(h^h>>>16); return h;} function hashMerge(a,b){ return a^b+0x9E3779B9+(a<<6)+(a>>2)|0;} var Immutable={ Iterable:Iterable, Seq:Seq, Collection:Collection, Map:Map, OrderedMap:OrderedMap, List:List, Stack:Stack, Set:Set, OrderedSet:OrderedSet, Record:Record, Range:Range, Repeat:Repeat, is:is, fromJS:fromJS}; return Immutable;}); }); __d('NavigatorBreadcrumbNavigationBar',function(global, require, module, exports) { 'use strict'; var NavigatorBreadcrumbNavigationBarStyles=require('NavigatorBreadcrumbNavigationBarStyles'); var NavigatorNavigationBarStylesAndroid=require('NavigatorNavigationBarStylesAndroid'); var NavigatorNavigationBarStylesIOS=require('NavigatorNavigationBarStylesIOS'); var Platform=require('Platform'); var React=require('React'); var StyleSheet=require('StyleSheet'); var View=require('View');var _require= require('immutable/dist/immutable.js');var Map=_require.Map; var invariant=require('invariant'); var Interpolators=NavigatorBreadcrumbNavigationBarStyles.Interpolators; var NavigatorNavigationBarStyles=Platform.OS==='android'? NavigatorNavigationBarStylesAndroid:NavigatorNavigationBarStylesIOS; var PropTypes=React.PropTypes; var CRUMB_PROPS=Interpolators.map(function(){return {style:{}};}); var ICON_PROPS=Interpolators.map(function(){return {style:{}};}); var SEPARATOR_PROPS=Interpolators.map(function(){return {style:{}};}); var TITLE_PROPS=Interpolators.map(function(){return {style:{}};}); var RIGHT_BUTTON_PROPS=Interpolators.map(function(){return {style:{}};}); var navStatePresentedIndex=function(navState){ if(navState.presentedIndex!==undefined){ return navState.presentedIndex;} return navState.observedTopOfStack;}; var initStyle=function(index,presentedIndex){ return index===presentedIndex?NavigatorBreadcrumbNavigationBarStyles.Center[index]: indexfromIndex?progress:1-progress; var oldDistToCenter=index-fromIndex; var newDistToCenter=index-toIndex; var interpolate; invariant( Interpolators[index], 'Cannot find breadcrumb interpolators for '+index); if(oldDistToCenter>0&&newDistToCenter===0|| newDistToCenter>0&&oldDistToCenter===0){ interpolate=Interpolators[index].RightToCenter;}else if(oldDistToCenter<0&&newDistToCenter===0|| newDistToCenter<0&&oldDistToCenter===0){ interpolate=Interpolators[index].CenterToLeft;}else if(oldDistToCenter===newDistToCenter){ interpolate=Interpolators[index].RightToCenter;}else { interpolate=Interpolators[index].RightToLeft;} if(interpolate.Crumb(CRUMB_PROPS[index].style,amount)){ this._setPropsIfExists('crumb_'+index,CRUMB_PROPS[index]);} if(interpolate.Icon(ICON_PROPS[index].style,amount)){ this._setPropsIfExists('icon_'+index,ICON_PROPS[index]);} if(interpolate.Separator(SEPARATOR_PROPS[index].style,amount)){ this._setPropsIfExists('separator_'+index,SEPARATOR_PROPS[index]);} if(interpolate.Title(TITLE_PROPS[index].style,amount)){ this._setPropsIfExists('title_'+index,TITLE_PROPS[index]);} var right=this.refs['right_'+index]; if(right&& interpolate.RightItem(RIGHT_BUTTON_PROPS[index].style,amount)){ right.setNativeProps(RIGHT_BUTTON_PROPS[index]);}}, updateProgress:function(progress,fromIndex,toIndex){ var max=Math.max(fromIndex,toIndex); var min=Math.min(fromIndex,toIndex); for(var index=min;index<=max;index++){ this._updateIndexProgress(progress,index,fromIndex,toIndex);}}, onAnimationStart:function(fromIndex,toIndex){ var max=Math.max(fromIndex,toIndex); var min=Math.min(fromIndex,toIndex); for(var index=min;index<=max;index++){ this._setRenderViewsToHardwareTextureAndroid(index,true);}}, onAnimationEnd:function(){ var max=this.props.navState.routeStack.length-1; for(var index=0;index<=max;index++){ this._setRenderViewsToHardwareTextureAndroid(index,false);}}, _setRenderViewsToHardwareTextureAndroid:function(index,renderToHardwareTexture){ var props={ renderToHardwareTextureAndroid:renderToHardwareTexture}; this._setPropsIfExists('icon_'+index,props); this._setPropsIfExists('separator_'+index,props); this._setPropsIfExists('title_'+index,props); this._setPropsIfExists('right_'+index,props);}, componentWillMount:function(){ this._descriptors={ crumb:new Map(), title:new Map(), right:new Map()};}, render:function(){ var navState=this.props.navState; var icons=navState&&navState.routeStack.map(this._getBreadcrumb); var titles=navState.routeStack.map(this._getTitle); var buttons=navState.routeStack.map(this._getRightButton); return ( React.createElement(View,{style:[styles.breadCrumbContainer,this.props.style]}, titles, icons, buttons));}, _getBreadcrumb:function(route,index){ if(this._descriptors.crumb.has(route)){ return this._descriptors.crumb.get(route);} var navBarRouteMapper=this.props.routeMapper; var firstStyles=initStyle(index,navStatePresentedIndex(this.props.navState)); var breadcrumbDescriptor= React.createElement(View,{ref:'crumb_'+index,style:firstStyles.Crumb}, React.createElement(View,{ref:'icon_'+index,style:firstStyles.Icon}, navBarRouteMapper.iconForRoute(route,this.props.navigator)), React.createElement(View,{ref:'separator_'+index,style:firstStyles.Separator}, navBarRouteMapper.separatorForRoute(route,this.props.navigator))); this._descriptors.crumb=this._descriptors.crumb.set(route,breadcrumbDescriptor); return breadcrumbDescriptor;}, _getTitle:function(route,index){ if(this._descriptors.title.has(route)){ return this._descriptors.title.get(route);} var titleContent=this.props.routeMapper.titleContentForRoute( this.props.navState.routeStack[index], this.props.navigator); var firstStyles=initStyle(index,navStatePresentedIndex(this.props.navState)); var titleDescriptor= React.createElement(View,{ref:'title_'+index,style:firstStyles.Title}, titleContent); this._descriptors.title=this._descriptors.title.set(route,titleDescriptor); return titleDescriptor;}, _getRightButton:function(route,index){ if(this._descriptors.right.has(route)){ return this._descriptors.right.get(route);} var rightContent=this.props.routeMapper.rightContentForRoute( this.props.navState.routeStack[index], this.props.navigator); if(!rightContent){ this._descriptors.right=this._descriptors.right.set(route,null); return null;} var firstStyles=initStyle(index,navStatePresentedIndex(this.props.navState)); var rightButtonDescriptor= React.createElement(View,{ref:'right_'+index,style:firstStyles.RightItem}, rightContent); this._descriptors.right=this._descriptors.right.set(route,rightButtonDescriptor); return rightButtonDescriptor;}, _setPropsIfExists:function(ref,props){ var ref=this.refs[ref]; ref&&ref.setNativeProps(props);}}); var styles=StyleSheet.create({ breadCrumbContainer:{ overflow:'hidden', position:'absolute', height:NavigatorNavigationBarStyles.General.TotalNavHeight, top:0, left:0, right:0}}); module.exports=NavigatorBreadcrumbNavigationBar; }); __d('NavigatorBreadcrumbNavigationBarStyles',function(global, require, module, exports) { 'use strict'; var Dimensions=require('Dimensions'); var NavigatorNavigationBarStylesIOS=require('NavigatorNavigationBarStylesIOS'); var buildStyleInterpolator=require('buildStyleInterpolator'); var merge=require('merge'); var SCREEN_WIDTH=Dimensions.get('window').width; var STATUS_BAR_HEIGHT=NavigatorNavigationBarStylesIOS.General.StatusBarHeight; var NAV_BAR_HEIGHT=NavigatorNavigationBarStylesIOS.General.NavBarHeight; var SPACING=4; var ICON_WIDTH=40; var SEPARATOR_WIDTH=9; var CRUMB_WIDTH=ICON_WIDTH+SEPARATOR_WIDTH; var OPACITY_RATIO=100; var ICON_INACTIVE_OPACITY=0.6; var MAX_BREADCRUMBS=10; var CRUMB_BASE={ position:'absolute', flexDirection:'row', top:STATUS_BAR_HEIGHT, width:CRUMB_WIDTH, height:NAV_BAR_HEIGHT, backgroundColor:'transparent'}; var ICON_BASE={ width:ICON_WIDTH, height:NAV_BAR_HEIGHT}; var SEPARATOR_BASE={ width:SEPARATOR_WIDTH, height:NAV_BAR_HEIGHT}; var TITLE_BASE={ position:'absolute', top:STATUS_BAR_HEIGHT, height:NAV_BAR_HEIGHT, backgroundColor:'transparent'}; var FIRST_TITLE_BASE=merge(TITLE_BASE,{ left:0, right:0, alignItems:'center', height:NAV_BAR_HEIGHT}); var RIGHT_BUTTON_BASE={ position:'absolute', top:STATUS_BAR_HEIGHT, right:SPACING, overflow:'hidden', opacity:1, height:NAV_BAR_HEIGHT, backgroundColor:'transparent'}; var LEFT=[]; var CENTER=[]; var RIGHT=[]; for(var i=0;i= '+( anim.threshold+' ? '+anim.to+' : '+anim.from)+';\n');}; var computeNextValIdentity=function(anim){ return ' nextScalarVal = value;\n';}; var operationVar=function(name){ return name+'ReuseOp';}; var createReusableOperationVars=function(anims){ var ret=''; for(var name in anims){ if(ShouldAllocateReusableOperationVars[name]){ ret+='var '+operationVar(name)+' = [];\n';}} return ret;}; var newlines=function(statements){ return '\n'+statements.join('\n')+'\n';}; var computeNextMatrixOperationField=function(anim,name,dimension,index){ var fieldAccess=operationVar(name)+'['+index+']'; if(anim.from[dimension]!==undefined&&anim.to[dimension]!==undefined){ return ' '+anim.from[dimension]!==anim.to[dimension]? computeNextValLinear(anim,anim.from[dimension],anim.to[dimension],fieldAccess): fieldAccess+' = '+anim.from[dimension]+';';}else { return ' '+fieldAccess+' = '+InitialOperationField[name][index]+';';}}; var unrolledVars=[]; for(var varIndex=0;varIndex<16;varIndex++){ unrolledVars.push('m'+varIndex);} var setNextMatrixAndDetectChange=function(orderedMatrixOperations){ var fn=[ ' var transformMatrix = result.transformMatrix !== undefined ? '+ 'result.transformMatrix : (result.transformMatrix = []);']; fn.push.apply( fn, inline(MatrixOps.unroll,['transformMatrix'].concat(unrolledVars))); for(var i=0;ifromIndex?progress:1-progress; var oldDistToCenter=index-fromIndex; var newDistToCenter=index-toIndex; var interpolate; if(oldDistToCenter>0&&newDistToCenter===0|| newDistToCenter>0&&oldDistToCenter===0){ interpolate=this.props.navigationStyles.Interpolators.RightToCenter;}else if(oldDistToCenter<0&&newDistToCenter===0|| newDistToCenter<0&&oldDistToCenter===0){ interpolate=this.props.navigationStyles.Interpolators.CenterToLeft;}else if(oldDistToCenter===newDistToCenter){ interpolate=this.props.navigationStyles.Interpolators.RightToCenter;}else { interpolate=this.props.navigationStyles.Interpolators.RightToLeft;} COMPONENT_NAMES.forEach(function(componentName){ var component=this._components[componentName].get(this.props.navState.routeStack[index]); var props=this._getReusableProps(componentName,index); if(component&&interpolate[componentName](props.style,amount)){ component.setNativeProps(props);}}, this);}, updateProgress:function( progress, fromIndex, toIndex) { var max=Math.max(fromIndex,toIndex); var min=Math.min(fromIndex,toIndex); for(var index=min;index<=max;index++){ this._updateIndexProgress(progress,index,fromIndex,toIndex);}}, render:function(){ var navBarStyle={ height:this.props.navigationStyles.General.TotalNavHeight}; var navState=this.props.navState; var components=COMPONENT_NAMES.map(function(componentName){ return navState.routeStack.map( this._getComponent.bind(this,componentName));}, this); return ( React.createElement(View,{style:[styles.navBarContainer,navBarStyle,this.props.style]}, components));}, _getComponent:function( componentName, route, index) {var _this2=this; if(this._descriptors[componentName].includes(route)){ return this._descriptors[componentName].get(route);} var rendered=null; var content=this.props.routeMapper[componentName]( this.props.navState.routeStack[index], this.props.navigator, index, this.props.navState); if(!content){ return null;} var initialStage=index===navStatePresentedIndex(this.props.navState)? this.props.navigationStyles.Stages.Center: this.props.navigationStyles.Stages.Left; rendered= React.createElement(View,{ ref:function(ref){ _this2._components[componentName]=_this2._components[componentName].set(route,ref);}, style:initialStage[componentName]}, content); this._descriptors[componentName]=this._descriptors[componentName].set(route,rendered); return rendered;}}); var styles=StyleSheet.create({ navBarContainer:{ position:'absolute', top:0, left:0, right:0, backgroundColor:'transparent'}}); module.exports=NavigatorNavigationBar; }); __d('StaticContainer.react',function(global, require, module, exports) { var React=require('React'); var onlyChild=require('onlyChild');var StaticContainer=(function(_React$Component){babelHelpers.inherits(StaticContainer,_React$Component);function StaticContainer(){babelHelpers.classCallCheck(this,StaticContainer);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(StaticContainer).apply(this,arguments));}babelHelpers.createClass(StaticContainer,[{key:'shouldComponentUpdate',value:function shouldComponentUpdate( nextProps){ return !!nextProps.shouldUpdate;}},{key:'render',value:function render() { var child=this.props.children; return child===null||child===false?null:onlyChild(child);}}]);return StaticContainer;})(React.Component); module.exports=StaticContainer; }); __d('NavigatorSceneConfigs',function(global, require, module, exports) { 'use strict'; var Dimensions=require('Dimensions'); var PixelRatio=require('PixelRatio'); var buildStyleInterpolator=require('buildStyleInterpolator'); var SCREEN_WIDTH=Dimensions.get('window').width; var SCREEN_HEIGHT=Dimensions.get('window').height; var FadeToTheLeft={ transformTranslate:{ from:{x:0,y:0,z:0}, to:{x:-Math.round(Dimensions.get('window').width*0.3),y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, transformScale:{ from:{x:1,y:1,z:1}, to:{x:0.95,y:0.95,z:1}, min:0, max:1, type:'linear', extrapolate:true}, opacity:{ from:1, to:0.3, min:0, max:1, type:'linear', extrapolate:false, round:100}, translateX:{ from:0, to:-Math.round(Dimensions.get('window').width*0.3), min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, scaleX:{ from:1, to:0.95, min:0, max:1, type:'linear', extrapolate:true}, scaleY:{ from:1, to:0.95, min:0, max:1, type:'linear', extrapolate:true}}; var FadeToTheRight=babelHelpers.extends({}, FadeToTheLeft,{ transformTranslate:{ from:{x:0,y:0,z:0}, to:{x:Math.round(SCREEN_WIDTH*0.3),y:0,z:0}}, translateX:{ from:0, to:Math.round(SCREEN_WIDTH*0.3)}}); var FadeIn={ opacity:{ from:0, to:1, min:0.5, max:1, type:'linear', extrapolate:false, round:100}}; var FadeOut={ opacity:{ from:1, to:0, min:0, max:0.5, type:'linear', extrapolate:false, round:100}}; var ToTheLeft={ transformTranslate:{ from:{x:0,y:0,z:0}, to:{x:-Dimensions.get('window').width,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, opacity:{ value:1.0, type:'constant'}, translateX:{ from:0, to:-Dimensions.get('window').width, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}}; var ToTheUp={ transformTranslate:{ from:{x:0,y:0,z:0}, to:{x:0,y:-Dimensions.get('window').height,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, opacity:{ value:1.0, type:'constant'}, translateY:{ from:0, to:-Dimensions.get('window').height, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}}; var ToTheDown={ transformTranslate:{ from:{x:0,y:0,z:0}, to:{x:0,y:Dimensions.get('window').height,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, opacity:{ value:1.0, type:'constant'}, translateY:{ from:0, to:Dimensions.get('window').height, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}}; var FromTheRight={ opacity:{ value:1.0, type:'constant'}, transformTranslate:{ from:{x:Dimensions.get('window').width,y:0,z:0}, to:{x:0,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, translateX:{ from:Dimensions.get('window').width, to:0, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, scaleX:{ value:1, type:'constant'}, scaleY:{ value:1, type:'constant'}}; var FromTheLeft=babelHelpers.extends({}, FromTheRight,{ transformTranslate:{ from:{x:-SCREEN_WIDTH,y:0,z:0}, to:{x:0,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, translateX:{ from:-SCREEN_WIDTH, to:0, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}}); var FromTheDown=babelHelpers.extends({}, FromTheRight,{ transformTranslate:{ from:{y:SCREEN_HEIGHT,x:0,z:0}, to:{x:0,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, translateY:{ from:SCREEN_HEIGHT, to:0, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}}); var FromTheTop=babelHelpers.extends({}, FromTheRight,{ transformTranslate:{ from:{y:-SCREEN_HEIGHT,x:0,z:0}, to:{x:0,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, translateY:{ from:-SCREEN_HEIGHT, to:0, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}}); var ToTheBack={ transformTranslate:{ from:{x:0,y:0,z:0}, to:{x:0,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, transformScale:{ from:{x:1,y:1,z:1}, to:{x:0.95,y:0.95,z:1}, min:0, max:1, type:'linear', extrapolate:true}, opacity:{ from:1, to:0.3, min:0, max:1, type:'linear', extrapolate:false, round:100}, scaleX:{ from:1, to:0.95, min:0, max:1, type:'linear', extrapolate:true}, scaleY:{ from:1, to:0.95, min:0, max:1, type:'linear', extrapolate:true}}; var FromTheFront={ opacity:{ value:1.0, type:'constant'}, transformTranslate:{ from:{x:0,y:Dimensions.get('window').height,z:0}, to:{x:0,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, translateY:{ from:Dimensions.get('window').height, to:0, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, scaleX:{ value:1, type:'constant'}, scaleY:{ value:1, type:'constant'}}; var ToTheBackAndroid={ opacity:{ value:1, type:'constant'}}; var FromTheFrontAndroid={ opacity:{ from:0, to:1, min:0.5, max:1, type:'linear', extrapolate:false, round:100}, transformTranslate:{ from:{x:0,y:100,z:0}, to:{x:0,y:0,z:0}, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}, translateY:{ from:100, to:0, min:0, max:1, type:'linear', extrapolate:true, round:PixelRatio.get()}}; var BaseOverswipeConfig={ frictionConstant:1, frictionByDistance:1.5}; var BaseLeftToRightGesture={ isDetachable:false, gestureDetectMovement:2, notMoving:0.3, directionRatio:0.66, snapVelocity:2, edgeHitWidth:30, stillCompletionRatio:3/5, fullDistance:SCREEN_WIDTH, direction:'left-to-right'}; var BaseRightToLeftGesture=babelHelpers.extends({}, BaseLeftToRightGesture,{ direction:'right-to-left'}); var BaseDownUpGesture=babelHelpers.extends({}, BaseLeftToRightGesture,{ fullDistance:SCREEN_HEIGHT, direction:'down-to-up'}); var BaseUpDownGesture=babelHelpers.extends({}, BaseLeftToRightGesture,{ fullDistance:SCREEN_HEIGHT, direction:'up-to-down'}); var BaseConfig={ gestures:{ pop:BaseLeftToRightGesture}, springFriction:26, springTension:200, defaultTransitionVelocity:1.5, animationInterpolators:{ into:buildStyleInterpolator(FromTheRight), out:buildStyleInterpolator(FadeToTheLeft)}}; var NavigatorSceneConfigs={ PushFromRight:babelHelpers.extends({}, BaseConfig), FloatFromRight:babelHelpers.extends({}, BaseConfig), FloatFromLeft:babelHelpers.extends({}, BaseConfig,{ animationInterpolators:{ into:buildStyleInterpolator(FromTheLeft), out:buildStyleInterpolator(FadeToTheRight)}}), FloatFromBottom:babelHelpers.extends({}, BaseConfig,{ gestures:{ pop:babelHelpers.extends({}, BaseLeftToRightGesture,{ edgeHitWidth:150, direction:'top-to-bottom', fullDistance:SCREEN_HEIGHT})}, animationInterpolators:{ into:buildStyleInterpolator(FromTheFront), out:buildStyleInterpolator(ToTheBack)}}), FloatFromBottomAndroid:babelHelpers.extends({}, BaseConfig,{ gestures:null, defaultTransitionVelocity:3, springFriction:20, animationInterpolators:{ into:buildStyleInterpolator(FromTheFrontAndroid), out:buildStyleInterpolator(ToTheBackAndroid)}}), FadeAndroid:babelHelpers.extends({}, BaseConfig,{ gestures:null, animationInterpolators:{ into:buildStyleInterpolator(FadeIn), out:buildStyleInterpolator(FadeOut)}}), HorizontalSwipeJump:babelHelpers.extends({}, BaseConfig,{ gestures:{ jumpBack:babelHelpers.extends({}, BaseLeftToRightGesture,{ overswipe:BaseOverswipeConfig, edgeHitWidth:null, isDetachable:true}), jumpForward:babelHelpers.extends({}, BaseRightToLeftGesture,{ overswipe:BaseOverswipeConfig, edgeHitWidth:null, isDetachable:true})}, animationInterpolators:{ into:buildStyleInterpolator(FromTheRight), out:buildStyleInterpolator(ToTheLeft)}}), VerticalUpSwipeJump:babelHelpers.extends({}, BaseConfig,{ gestures:{ jumpBack:babelHelpers.extends({}, BaseDownUpGesture,{ overswipe:BaseOverswipeConfig, edgeHitWidth:null, isDetachable:true}), jumpForward:babelHelpers.extends({}, BaseDownUpGesture,{ overswipe:BaseOverswipeConfig, edgeHitWidth:null, isDetachable:true})}, animationInterpolators:{ into:buildStyleInterpolator(FromTheDown), out:buildStyleInterpolator(ToTheUp)}}), VerticalDownSwipeJump:babelHelpers.extends({}, BaseConfig,{ gestures:{ jumpBack:babelHelpers.extends({}, BaseUpDownGesture,{ overswipe:BaseOverswipeConfig, edgeHitWidth:null, isDetachable:true}), jumpForward:babelHelpers.extends({}, BaseUpDownGesture,{ overswipe:BaseOverswipeConfig, edgeHitWidth:null, isDetachable:true})}, animationInterpolators:{ into:buildStyleInterpolator(FromTheTop), out:buildStyleInterpolator(ToTheDown)}})}; module.exports=NavigatorSceneConfigs; }); __d('PanResponder',function(global, require, module, exports) { "use strict"; var TouchHistoryMath=require('TouchHistoryMath'); var currentCentroidXOfTouchesChangedAfter= TouchHistoryMath.currentCentroidXOfTouchesChangedAfter; var currentCentroidYOfTouchesChangedAfter= TouchHistoryMath.currentCentroidYOfTouchesChangedAfter; var previousCentroidXOfTouchesChangedAfter= TouchHistoryMath.previousCentroidXOfTouchesChangedAfter; var previousCentroidYOfTouchesChangedAfter= TouchHistoryMath.previousCentroidYOfTouchesChangedAfter; var currentCentroidX=TouchHistoryMath.currentCentroidX; var currentCentroidY=TouchHistoryMath.currentCentroidY; var PanResponder={ _initializeGestureState:function(gestureState){ gestureState.moveX=0; gestureState.moveY=0; gestureState.x0=0; gestureState.y0=0; gestureState.dx=0; gestureState.dy=0; gestureState.vx=0; gestureState.vy=0; gestureState.numberActiveTouches=0; gestureState._accountsForMovesUpTo=0;}, _updateGestureStateOnMove:function(gestureState,touchHistory){ gestureState.numberActiveTouches=touchHistory.numberActiveTouches; gestureState.moveX=currentCentroidXOfTouchesChangedAfter( touchHistory, gestureState._accountsForMovesUpTo); gestureState.moveY=currentCentroidYOfTouchesChangedAfter( touchHistory, gestureState._accountsForMovesUpTo); var movedAfter=gestureState._accountsForMovesUpTo; var prevX=previousCentroidXOfTouchesChangedAfter(touchHistory,movedAfter); var x=currentCentroidXOfTouchesChangedAfter(touchHistory,movedAfter); var prevY=previousCentroidYOfTouchesChangedAfter(touchHistory,movedAfter); var y=currentCentroidYOfTouchesChangedAfter(touchHistory,movedAfter); var nextDX=gestureState.dx+(x-prevX); var nextDY=gestureState.dy+(y-prevY); var dt= touchHistory.mostRecentTimeStamp-gestureState._accountsForMovesUpTo; gestureState.vx=(nextDX-gestureState.dx)/dt; gestureState.vy=(nextDY-gestureState.dy)/dt; gestureState.dx=nextDX; gestureState.dy=nextDY; gestureState._accountsForMovesUpTo=touchHistory.mostRecentTimeStamp;}, create:function(config){ var gestureState={ stateID:Math.random()}; PanResponder._initializeGestureState(gestureState); var panHandlers={ onStartShouldSetResponder:function(e){ return config.onStartShouldSetPanResponder===undefined?false: config.onStartShouldSetPanResponder(e,gestureState);}, onMoveShouldSetResponder:function(e){ return config.onMoveShouldSetPanResponder===undefined?false: config.onMoveShouldSetPanResponder(e,gestureState);}, onStartShouldSetResponderCapture:function(e){ if(e.nativeEvent.touches.length===1){ PanResponder._initializeGestureState(gestureState);} gestureState.numberActiveTouches=e.touchHistory.numberActiveTouches; return config.onStartShouldSetPanResponderCapture!==undefined? config.onStartShouldSetPanResponderCapture(e,gestureState):false;}, onMoveShouldSetResponderCapture:function(e){ var touchHistory=e.touchHistory; if(gestureState._accountsForMovesUpTo===touchHistory.mostRecentTimeStamp){ return false;} PanResponder._updateGestureStateOnMove(gestureState,touchHistory); return config.onMoveShouldSetPanResponderCapture? config.onMoveShouldSetPanResponderCapture(e,gestureState):false;}, onResponderGrant:function(e){ gestureState.x0=currentCentroidX(e.touchHistory); gestureState.y0=currentCentroidY(e.touchHistory); gestureState.dx=0; gestureState.dy=0; config.onPanResponderGrant&&config.onPanResponderGrant(e,gestureState); return config.onShouldBlockNativeResponder===undefined?true: config.onShouldBlockNativeResponder();}, onResponderReject:function(e){ config.onPanResponderReject&&config.onPanResponderReject(e,gestureState);}, onResponderRelease:function(e){ config.onPanResponderRelease&&config.onPanResponderRelease(e,gestureState); PanResponder._initializeGestureState(gestureState);}, onResponderStart:function(e){ var touchHistory=e.touchHistory; gestureState.numberActiveTouches=touchHistory.numberActiveTouches; config.onPanResponderStart&&config.onPanResponderStart(e,gestureState);}, onResponderMove:function(e){ var touchHistory=e.touchHistory; if(gestureState._accountsForMovesUpTo===touchHistory.mostRecentTimeStamp){ return;} PanResponder._updateGestureStateOnMove(gestureState,touchHistory); config.onPanResponderMove&&config.onPanResponderMove(e,gestureState);}, onResponderEnd:function(e){ var touchHistory=e.touchHistory; gestureState.numberActiveTouches=touchHistory.numberActiveTouches; config.onPanResponderEnd&&config.onPanResponderEnd(e,gestureState);}, onResponderTerminate:function(e){ config.onPanResponderTerminate&& config.onPanResponderTerminate(e,gestureState); PanResponder._initializeGestureState(gestureState);}, onResponderTerminationRequest:function(e){ return config.onPanResponderTerminationRequest===undefined?true: config.onPanResponderTerminationRequest(e,gestureState);}}; return {panHandlers:panHandlers};}}; module.exports=PanResponder; }); __d('TouchHistoryMath',function(global, require, module, exports) { "use strict"; var TouchHistoryMath={ centroidDimension:function(touchHistory,touchesChangedAfter,isXAxis,ofCurrent){ var touchBank=touchHistory.touchBank; var total=0; var count=0; var oneTouchData=touchHistory.numberActiveTouches===1? touchHistory.touchBank[touchHistory.indexOfSingleActiveTouch]:null; if(oneTouchData!==null){ if(oneTouchData.touchActive&&oneTouchData.currentTimeStamp>touchesChangedAfter){ total+=ofCurrent&&isXAxis?oneTouchData.currentPageX: ofCurrent&&!isXAxis?oneTouchData.currentPageY: !ofCurrent&&isXAxis?oneTouchData.previousPageX: oneTouchData.previousPageY; count=1;}}else { for(var i=0;i=touchesChangedAfter){ var toAdd; if(ofCurrent&&isXAxis){ toAdd=touchTrack.currentPageX;}else if(ofCurrent&&!isXAxis){ toAdd=touchTrack.currentPageY;}else if(!ofCurrent&&isXAxis){ toAdd=touchTrack.previousPageX;}else { toAdd=touchTrack.previousPageY;} total+=toAdd; count++;}}} return count>0?total/count:TouchHistoryMath.noCentroid;}, currentCentroidXOfTouchesChangedAfter:function(touchHistory,touchesChangedAfter){ return TouchHistoryMath.centroidDimension( touchHistory, touchesChangedAfter, true, true);}, currentCentroidYOfTouchesChangedAfter:function(touchHistory,touchesChangedAfter){ return TouchHistoryMath.centroidDimension( touchHistory, touchesChangedAfter, false, true);}, previousCentroidXOfTouchesChangedAfter:function(touchHistory,touchesChangedAfter){ return TouchHistoryMath.centroidDimension( touchHistory, touchesChangedAfter, true, false);}, previousCentroidYOfTouchesChangedAfter:function(touchHistory,touchesChangedAfter){ return TouchHistoryMath.centroidDimension( touchHistory, touchesChangedAfter, false, false);}, currentCentroidX:function(touchHistory){ return TouchHistoryMath.centroidDimension( touchHistory, 0, true, true);}, currentCentroidY:function(touchHistory){ return TouchHistoryMath.centroidDimension( touchHistory, 0, false, true);}, noCentroid:-1}; module.exports=TouchHistoryMath; }); __d('clamp',function(global, require, module, exports) { function clamp(min,value,max){ if(valuemax){ return max;} return value;} module.exports=clamp; }); __d('rebound/rebound.js',function(global, require, module, exports) { ( function(){ var rebound={}; var util=rebound.util={}; var concat=Array.prototype.concat; var slice=Array.prototype.slice; util.bind=function bind(func,context){ var args=slice.call(arguments,2); return function(){ func.apply(context,concat.call(args,slice.call(arguments)));};}; util.extend=function extend(target,source){ for(var key in source){ if(source.hasOwnProperty(key)){ target[key]=source[key];}}}; var SpringSystem=rebound.SpringSystem=function SpringSystem(looper){ this._springRegistry={}; this._activeSprings=[]; this.listeners=[]; this._idleSpringIndices=[]; this.looper=looper||new AnimationLooper(); this.looper.springSystem=this;}; util.extend(SpringSystem.prototype,{ _springRegistry:null, _isIdle:true, _lastTimeMillis:-1, _activeSprings:null, listeners:null, _idleSpringIndices:null, setLooper:function(looper){ this.looper=looper; looper.springSystem=this;}, createSpring:function(tension,friction){ var springConfig; if(tension===undefined||friction===undefined){ springConfig=SpringConfig.DEFAULT_ORIGAMI_SPRING_CONFIG;}else { springConfig= SpringConfig.fromOrigamiTensionAndFriction(tension,friction);} return this.createSpringWithConfig(springConfig);}, createSpringWithBouncinessAndSpeed:function(bounciness,speed){ var springConfig; if(bounciness===undefined||speed===undefined){ springConfig=SpringConfig.DEFAULT_ORIGAMI_SPRING_CONFIG;}else { springConfig= SpringConfig.fromBouncinessAndSpeed(bounciness,speed);} return this.createSpringWithConfig(springConfig);}, createSpringWithConfig:function(springConfig){ var spring=new Spring(this); this.registerSpring(spring); spring.setSpringConfig(springConfig); return spring;}, getIsIdle:function(){ return this._isIdle;}, getSpringById:function(id){ return this._springRegistry[id];}, getAllSprings:function(){ var vals=[]; for(var id in this._springRegistry){ if(this._springRegistry.hasOwnProperty(id)){ vals.push(this._springRegistry[id]);}} return vals;}, registerSpring:function(spring){ this._springRegistry[spring.getId()]=spring;}, deregisterSpring:function(spring){ removeFirst(this._activeSprings,spring); delete this._springRegistry[spring.getId()];}, advance:function(time,deltaTime){ while(this._idleSpringIndices.length>0){this._idleSpringIndices.pop();} for(var i=0,len=this._activeSprings.length;i0){ var idx=this._idleSpringIndices.pop(); idx>=0&&this._activeSprings.splice(idx,1);}}, loop:function(currentTimeMillis){ var listener; if(this._lastTimeMillis===-1){ this._lastTimeMillis=currentTimeMillis-1;} var ellapsedMillis=currentTimeMillis-this._lastTimeMillis; this._lastTimeMillis=currentTimeMillis; var i=0,len=this.listeners.length; for(i=0;i0&&( startend|| start>end&&this.getCurrentValue()Spring.MAX_DELTA_TIME_SEC){ adjustedDeltaTime=Spring.MAX_DELTA_TIME_SEC;} this._timeAccumulator+=adjustedDeltaTime; var tension=this._springConfig.tension, friction=this._springConfig.friction, position=this._currentState.position, velocity=this._currentState.velocity, tempPosition=this._tempState.position, tempVelocity=this._tempState.velocity, aVelocity,aAcceleration, bVelocity,bAcceleration, cVelocity,cAcceleration, dVelocity,dAcceleration, dxdt,dvdt; while(this._timeAccumulator>=Spring.SOLVER_TIMESTEP_SEC){ this._timeAccumulator-=Spring.SOLVER_TIMESTEP_SEC; if(this._timeAccumulator0){ this._interpolate(this._timeAccumulator/Spring.SOLVER_TIMESTEP_SEC);} if(this.isAtRest()|| this._overshootClampingEnabled&&this.isOvershooting()){ if(this._springConfig.tension>0){ this._startValue=this._endValue; this._currentState.position=this._endValue;}else { this._endValue=this._currentState.position; this._startValue=this._endValue;} this.setVelocity(0); isAtRest=true;} var notifyActivate=false; if(this._wasAtRest){ this._wasAtRest=false; notifyActivate=true;} var notifyAtRest=false; if(isAtRest){ this._wasAtRest=true; notifyAtRest=true;} this.notifyPositionUpdated(notifyActivate,notifyAtRest);}, notifyPositionUpdated:function(notifyActivate,notifyAtRest){ for(var i=0,len=this.listeners.length;i18&&tension<=44){ friction=this.b3Friction2(tension);}else { friction=this.b3Friction3(tension);} return friction;}}); util.extend(SpringConfig,{ fromOrigamiTensionAndFriction:function(tension,friction){ return new SpringConfig( OrigamiValueConverter.tensionFromOrigamiValue(tension), OrigamiValueConverter.frictionFromOrigamiValue(friction));}, fromBouncinessAndSpeed:function(bounciness,speed){ var bouncyConversion=new rebound.BouncyConversion(bounciness,speed); return this.fromOrigamiTensionAndFriction( bouncyConversion.bouncyTension, bouncyConversion.bouncyFriction);}, coastingConfigWithOrigamiFriction:function(friction){ return new SpringConfig( 0, OrigamiValueConverter.frictionFromOrigamiValue(friction));}}); SpringConfig.DEFAULT_ORIGAMI_SPRING_CONFIG= SpringConfig.fromOrigamiTensionAndFriction(40,7); util.extend(SpringConfig.prototype,{friction:0,tension:0}); var colorCache={}; util.hexToRGB=function(color){ if(colorCache[color]){ return colorCache[color];} color=color.replace('#',''); if(color.length===3){ color=color[0]+color[0]+color[1]+color[1]+color[2]+color[2];} var parts=color.match(/.{2}/g); var ret={ r:parseInt(parts[0],16), g:parseInt(parts[1],16), b:parseInt(parts[2],16)}; colorCache[color]=ret; return ret;}; util.rgbToHex=function(r,g,b){ r=r.toString(16); g=g.toString(16); b=b.toString(16); r=r.length<2?'0'+r:r; g=g.length<2?'0'+g:g; b=b.length<2?'0'+b:b; return '#'+r+g+b;}; var MathUtil=rebound.MathUtil={ mapValueInRange:function(value,fromLow,fromHigh,toLow,toHigh){ var fromRangeSize=fromHigh-fromLow; var toRangeSize=toHigh-toLow; var valueScale=(value-fromLow)/fromRangeSize; return toLow+valueScale*toRangeSize;}, interpolateColor: function(val,startColor,endColor,fromLow,fromHigh,asRGB){ fromLow=fromLow===undefined?0:fromLow; fromHigh=fromHigh===undefined?1:fromHigh; startColor=util.hexToRGB(startColor); endColor=util.hexToRGB(endColor); var r=Math.floor( util.mapValueInRange(val,fromLow,fromHigh,startColor.r,endColor.r)); var g=Math.floor( util.mapValueInRange(val,fromLow,fromHigh,startColor.g,endColor.g)); var b=Math.floor( util.mapValueInRange(val,fromLow,fromHigh,startColor.b,endColor.b)); if(asRGB){ return 'rgb('+r+','+g+','+b+')';}else { return util.rgbToHex(r,g,b);}}, degreesToRadians:function(deg){ return deg*Math.PI/180;}, radiansToDegrees:function(rad){ return rad*180/Math.PI;}}; util.extend(util,MathUtil); function removeFirst(array,item){ var idx=array.indexOf(item); idx!=-1&&array.splice(idx,1);} var _onFrame; if(typeof window!=='undefined'){ _onFrame=window.requestAnimationFrame|| window.webkitRequestAnimationFrame|| window.mozRequestAnimationFrame|| window.msRequestAnimationFrame|| window.oRequestAnimationFrame|| function(callback){ window.setTimeout(callback,1000/60);};} if(!_onFrame&&typeof process!=='undefined'&&process.title==='node'){ _onFrame=setImmediate;} util.onFrame=function onFrame(func){ return _onFrame(func);}; if(typeof exports!='undefined'){ util.extend(exports,rebound);}else if(typeof window!='undefined'){ window.rebound=rebound;}})(); }); __d('NavigatorIOS',function(global, require, module, exports) { 'use strict'; var EventEmitter=require('EventEmitter'); var Image=require('Image'); var NavigationContext=require('NavigationContext'); var RCTNavigatorManager=require('NativeModules').NavigatorManager; var React=require('React'); var StaticContainer=require('StaticContainer.react'); var StyleSheet=require('StyleSheet'); var View=require('View'); var invariant=require('invariant'); var logError=require('logError'); var requireNativeComponent=require('requireNativeComponent'); var resolveAssetSource=require('resolveAssetSource'); var TRANSITIONER_REF='transitionerRef'; var PropTypes=React.PropTypes; var __uid=0; function getuid(){ return __uid++;} var NavigatorTransitionerIOS=React.createClass({displayName:'NavigatorTransitionerIOS', requestSchedulingNavigation:function(cb){ RCTNavigatorManager.requestSchedulingJavaScriptNavigation( React.findNodeHandle(this), logError, cb);}, render:function(){ return ( React.createElement(RCTNavigator,this.props));}}); var NavigatorIOS=React.createClass({displayName:'NavigatorIOS', propTypes:{ initialRoute:PropTypes.shape({ component:PropTypes.func.isRequired, title:PropTypes.string.isRequired, passProps:PropTypes.object, backButtonIcon:Image.propTypes.source, backButtonTitle:PropTypes.string, leftButtonIcon:Image.propTypes.source, leftButtonTitle:PropTypes.string, onLeftButtonPress:PropTypes.func, rightButtonIcon:Image.propTypes.source, rightButtonTitle:PropTypes.string, onRightButtonPress:PropTypes.func, wrapperStyle:View.propTypes.style}). isRequired, navigationBarHidden:PropTypes.bool, shadowHidden:PropTypes.bool, itemWrapperStyle:View.propTypes.style, tintColor:PropTypes.string, barTintColor:PropTypes.string, titleTextColor:PropTypes.string, translucent:PropTypes.bool}, navigator:undefined, navigationContext:new NavigationContext(), componentWillMount:function(){ this.navigator={ push:this.push, pop:this.pop, popN:this.popN, replace:this.replace, replacePrevious:this.replacePrevious, replacePreviousAndPop:this.replacePreviousAndPop, resetTo:this.resetTo, popToRoute:this.popToRoute, popToTop:this.popToTop, navigationContext:this.navigationContext}; this._emitWillFocus(this.state.routeStack[this.state.observedTopOfStack]);}, componentDidMount:function(){ this._emitDidFocus(this.state.routeStack[this.state.observedTopOfStack]);}, componentWillUnmount:function(){ this.navigationContext.dispose(); this.navigationContext=new NavigationContext();}, getInitialState:function(){ return { idStack:[getuid()], routeStack:[this.props.initialRoute], requestedTopOfStack:0, observedTopOfStack:0, progress:1, fromIndex:0, toIndex:0, makingNavigatorRequest:false, updatingAllIndicesAtOrBeyond:0};}, _toFocusOnNavigationComplete:undefined, _handleFocusRequest:function(item){ if(this.state.makingNavigatorRequest){ this._toFocusOnNavigationComplete=item;}else { this._getFocusEmitter().emit('focus',item);}}, _focusEmitter:undefined, _getFocusEmitter:function(){ var focusEmitter=this._focusEmitter; if(!focusEmitter){ focusEmitter=new EventEmitter(); this._focusEmitter=focusEmitter;} return focusEmitter;}, getChildContext:function() { return { onFocusRequested:this._handleFocusRequest, focusEmitter:this._getFocusEmitter()};}, childContextTypes:{ onFocusRequested:React.PropTypes.func, focusEmitter:React.PropTypes.instanceOf(EventEmitter)}, _tryLockNavigator:function(cb){ this.refs[TRANSITIONER_REF].requestSchedulingNavigation( function(acquiredLock){return acquiredLock&&cb();});}, _handleNavigatorStackChanged:function(e){ var newObservedTopOfStack=e.nativeEvent.stackLength-1; this._emitDidFocus(this.state.routeStack[newObservedTopOfStack]); invariant( newObservedTopOfStack<=this.state.requestedTopOfStack, 'No navigator item should be pushed without JS knowing about it %s %s',newObservedTopOfStack,this.state.requestedTopOfStack); var wasWaitingForConfirmation= this.state.requestedTopOfStack!==this.state.observedTopOfStack; if(wasWaitingForConfirmation){ invariant( newObservedTopOfStack===this.state.requestedTopOfStack, 'If waiting for observedTopOfStack to reach requestedTopOfStack, '+ 'the only valid observedTopOfStack should be requestedTopOfStack.');} var nextState={ observedTopOfStack:newObservedTopOfStack, makingNavigatorRequest:false, updatingAllIndicesAtOrBeyond:null, progress:1, toIndex:newObservedTopOfStack, fromIndex:newObservedTopOfStack}; this.setState(nextState,this._eliminateUnneededChildren);}, _eliminateUnneededChildren:function(){ var updatingAllIndicesAtOrBeyond= this.state.routeStack.length>this.state.observedTopOfStack+1? this.state.observedTopOfStack+1: null; this.setState({ idStack:this.state.idStack.slice(0,this.state.observedTopOfStack+1), routeStack:this.state.routeStack.slice(0,this.state.observedTopOfStack+1), requestedTopOfStack:this.state.observedTopOfStack, makingNavigatorRequest:true, updatingAllIndicesAtOrBeyond:updatingAllIndicesAtOrBeyond});}, _emitDidFocus:function(route){ this.navigationContext.emit('didfocus',{route:route});}, _emitWillFocus:function(route){ this.navigationContext.emit('willfocus',{route:route});}, push:function(route){var _this=this; invariant(!!route,'Must supply route to push'); if(this.state.requestedTopOfStack===this.state.observedTopOfStack){ this._tryLockNavigator(function(){ _this._emitWillFocus(route); var nextStack=_this.state.routeStack.concat([route]); var nextIDStack=_this.state.idStack.concat([getuid()]); _this.setState({ idStack:nextIDStack, routeStack:nextStack, requestedTopOfStack:nextStack.length-1, makingNavigatorRequest:true, updatingAllIndicesAtOrBeyond:nextStack.length-1});});}}, popN:function(n){var _this2=this; if(n===0){ return;} if(this.state.requestedTopOfStack===this.state.observedTopOfStack){ if(this.state.requestedTopOfStack>0){ this._tryLockNavigator(function(){ var newRequestedTopOfStack=_this2.state.requestedTopOfStack-n; invariant(newRequestedTopOfStack>=0,'Cannot pop below 0'); _this2._emitWillFocus(_this2.state.routeStack[newRequestedTopOfStack]); _this2.setState({ requestedTopOfStack:newRequestedTopOfStack, makingNavigatorRequest:true, updatingAllIndicesAtOrBeyond:null});});}}}, pop:function(){ this.popN(1);}, replaceAtIndex:function(route,index){ invariant(!!route,'Must supply route to replace'); if(index<0){ index+=this.state.routeStack.length;} if(this.state.routeStack.length<=index){ return;} var nextIDStack=this.state.idStack.slice(); var nextRouteStack=this.state.routeStack.slice(); nextIDStack[index]=getuid(); nextRouteStack[index]=route; this.setState({ idStack:nextIDStack, routeStack:nextRouteStack, makingNavigatorRequest:false, updatingAllIndicesAtOrBeyond:index}); this._emitWillFocus(route); this._emitDidFocus(route);}, replace:function(route){ this.replaceAtIndex(route,-1);}, replacePrevious:function(route){ this.replaceAtIndex(route,-2);}, popToTop:function(){ this.popToRoute(this.state.routeStack[0]);}, popToRoute:function(route){ var indexOfRoute=this.state.routeStack.indexOf(route); invariant( indexOfRoute!==-1, 'Calling pop to route for a route that doesn\'t exist!'); var numToPop=this.state.routeStack.length-indexOfRoute-1; this.popN(numToPop);}, replacePreviousAndPop:function(route){var _this3=this; if(this.state.requestedTopOfStack!==this.state.observedTopOfStack){ return;} if(this.state.routeStack.length<2){ return;} this._tryLockNavigator(function(){ _this3.replacePrevious(route); _this3.setState({ requestedTopOfStack:_this3.state.requestedTopOfStack-1, makingNavigatorRequest:true});});}, resetTo:function(route){ invariant(!!route,'Must supply route to push'); if(this.state.requestedTopOfStack!==this.state.observedTopOfStack){ return;} this.replaceAtIndex(route,0); this.popToRoute(route);}, handleNavigationComplete:function(e){ if(this._toFocusOnNavigationComplete){ this._getFocusEmitter().emit('focus',this._toFocusOnNavigationComplete); this._toFocusOnNavigationComplete=null;} this._handleNavigatorStackChanged(e);}, _routeToStackItem:function(route,i){ var Component=route.component; var shouldUpdateChild=this.state.updatingAllIndicesAtOrBeyond!==null&& this.state.updatingAllIndicesAtOrBeyond>=i; return ( React.createElement(StaticContainer,{key:'nav'+i,shouldUpdate:shouldUpdateChild}, React.createElement(RCTNavigatorItem,{ title:route.title, style:[ styles.stackItem, this.props.itemWrapperStyle, route.wrapperStyle], backButtonIcon:resolveAssetSource(route.backButtonIcon), backButtonTitle:route.backButtonTitle, leftButtonIcon:resolveAssetSource(route.leftButtonIcon), leftButtonTitle:route.leftButtonTitle, onNavLeftButtonTap:route.onLeftButtonPress, rightButtonIcon:resolveAssetSource(route.rightButtonIcon), rightButtonTitle:route.rightButtonTitle, onNavRightButtonTap:route.onRightButtonPress, navigationBarHidden:this.props.navigationBarHidden, shadowHidden:this.props.shadowHidden, tintColor:this.props.tintColor, barTintColor:this.props.barTintColor, translucent:this.props.translucent!==false, titleTextColor:this.props.titleTextColor}, React.createElement(Component,babelHelpers.extends({ navigator:this.navigator, route:route}, route.passProps)))));}, renderNavigationStackItems:function(){ var shouldRecurseToNavigator= this.state.makingNavigatorRequest|| this.state.updatingAllIndicesAtOrBeyond!==null; var items=shouldRecurseToNavigator? this.state.routeStack.map(this._routeToStackItem):null; return ( React.createElement(StaticContainer,{shouldUpdate:shouldRecurseToNavigator}, React.createElement(NavigatorTransitionerIOS,{ ref:TRANSITIONER_REF, style:styles.transitioner, vertical:this.props.vertical, requestedTopOfStack:this.state.requestedTopOfStack, onNavigationComplete:this.handleNavigationComplete}, items)));}, render:function(){ return ( React.createElement(View,{style:this.props.style}, this.renderNavigationStackItems()));}}); var styles=StyleSheet.create({ stackItem:{ backgroundColor:'white', overflow:'hidden', position:'absolute', top:0, left:0, right:0, bottom:0}, transitioner:{ flex:1}}); var RCTNavigator=requireNativeComponent('RCTNavigator'); var RCTNavigatorItem=requireNativeComponent('RCTNavItem'); module.exports=NavigatorIOS; }); __d('PickerIOS',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var React=require('React'); var ReactChildren=require('ReactChildren'); var ReactNativeViewAttributes=require('ReactNativeViewAttributes'); var RCTPickerIOSConsts=require('NativeModules').UIManager.RCTPicker.Constants; var StyleSheet=require('StyleSheet'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var merge=require('merge'); var PICKER='picker'; var PickerIOS=React.createClass({displayName:'PickerIOS', mixins:[NativeMethodsMixin], propTypes:babelHelpers.extends({}, View.propTypes,{ onValueChange:React.PropTypes.func, selectedValue:React.PropTypes.any}), getInitialState:function(){ return this._stateFromProps(this.props);}, componentWillReceiveProps:function(nextProps){ this.setState(this._stateFromProps(nextProps));}, _stateFromProps:function(props){ var selectedIndex=0; var items=[]; ReactChildren.forEach(props.children,function(child,index){ if(child.props.value===props.selectedValue){ selectedIndex=index;} items.push({value:child.props.value,label:child.props.label});}); return {selectedIndex:selectedIndex,items:items};}, render:function(){ return ( React.createElement(View,{style:this.props.style}, React.createElement(RCTPickerIOS,{ ref:PICKER, style:styles.pickerIOS, items:this.state.items, selectedIndex:this.state.selectedIndex, onChange:this._onChange})));}, _onChange:function(event){ if(this.props.onChange){ this.props.onChange(event);} if(this.props.onValueChange){ this.props.onValueChange(event.nativeEvent.newValue);} if(this.state.selectedIndex!==event.nativeEvent.newIndex){ this.refs[PICKER].setNativeProps({ selectedIndex:this.state.selectedIndex});}}}); PickerIOS.Item=React.createClass({displayName:'Item', propTypes:{ value:React.PropTypes.any, label:React.PropTypes.string}, render:function(){ return null;}}); var styles=StyleSheet.create({ pickerIOS:{ height:RCTPickerIOSConsts.ComponentHeight}}); var RCTPickerIOS=requireNativeComponent('RCTPicker',PickerIOS,{ nativeOnly:{ items:true, onChange:true, selectedIndex:true}}); module.exports=PickerIOS; }); __d('ProgressBarAndroid',function(global, require, module, exports) { 'use strict'; module.exports=require('UnimplementedView'); }); __d('ProgressViewIOS',function(global, require, module, exports) { 'use strict'; var Image=require('Image'); var NativeMethodsMixin=require('NativeMethodsMixin'); var NativeModules=require('NativeModules'); var PropTypes=require('ReactPropTypes'); var React=require('React'); var StyleSheet=require('StyleSheet'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var ProgressViewIOS=React.createClass({displayName:'ProgressViewIOS', mixins:[NativeMethodsMixin], propTypes:babelHelpers.extends({}, View.propTypes,{ progressViewStyle:PropTypes.oneOf(['default','bar']), progress:PropTypes.number, progressTintColor:PropTypes.string, trackTintColor:PropTypes.string, progressImage:Image.propTypes.source, trackImage:Image.propTypes.source}), render:function(){ return ( React.createElement(RCTProgressView,babelHelpers.extends({}, this.props,{ style:[styles.progressView,this.props.style]})));}}); var styles=StyleSheet.create({ progressView:{ height:NativeModules.ProgressViewManager.ComponentHeight}}); var RCTProgressView=requireNativeComponent( 'RCTProgressView', ProgressViewIOS); module.exports=ProgressViewIOS; }); __d('SegmentedControlIOS',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var NativeModules=require('NativeModules'); var PropTypes=require('ReactPropTypes'); var React=require('React'); var StyleSheet=require('StyleSheet'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var SEGMENTED_CONTROL_REFERENCE='segmentedcontrol'; var SegmentedControlIOS=React.createClass({displayName:'SegmentedControlIOS', mixins:[NativeMethodsMixin], propTypes:babelHelpers.extends({}, View.propTypes,{ values:PropTypes.arrayOf(PropTypes.string), selectedIndex:PropTypes.number, onValueChange:PropTypes.func, onChange:PropTypes.func, enabled:PropTypes.bool, tintColor:PropTypes.string, momentary:PropTypes.bool}), getDefaultProps:function(){ return { values:[], enabled:true};}, _onChange:function(event){ this.props.onChange&&this.props.onChange(event); this.props.onValueChange&&this.props.onValueChange(event.nativeEvent.value);}, render:function(){ return ( React.createElement(RCTSegmentedControl,babelHelpers.extends({}, this.props,{ ref:SEGMENTED_CONTROL_REFERENCE, style:[styles.segmentedControl,this.props.style], onChange:this._onChange})));}}); var styles=StyleSheet.create({ segmentedControl:{ height:NativeModules.SegmentedControlManager.ComponentHeight}}); var RCTSegmentedControl=requireNativeComponent( 'RCTSegmentedControl', SegmentedControlIOS); module.exports=SegmentedControlIOS; }); __d('SliderIOS',function(global, require, module, exports) { 'use strict'; var Image=require('Image'); var NativeMethodsMixin=require('NativeMethodsMixin'); var PropTypes=require('ReactPropTypes'); var React=require('React'); var StyleSheet=require('StyleSheet'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var SliderIOS=React.createClass({displayName:'SliderIOS', mixins:[NativeMethodsMixin], propTypes:babelHelpers.extends({}, View.propTypes,{ style:View.propTypes.style, value:PropTypes.number, step:PropTypes.number, minimumValue:PropTypes.number, maximumValue:PropTypes.number, minimumTrackTintColor:PropTypes.string, maximumTrackTintColor:PropTypes.string, disabled:PropTypes.bool, trackImage:Image.propTypes.source, onValueChange:PropTypes.func, onSlidingComplete:PropTypes.func}), getDefaultProps:function(){ return { disabled:false};}, render:function(){var _this=this; var onValueChange=this.props.onValueChange&&function(event){ _this.props.onValueChange&& _this.props.onValueChange(event.nativeEvent.value);}; var onSlidingComplete=this.props.onSlidingComplete&&function(event){ _this.props.onSlidingComplete&& _this.props.onSlidingComplete(event.nativeEvent.value);};var _props= this.props;var style=_props.style;var props=babelHelpers.objectWithoutProperties(_props,['style']); style=[styles.slider,this.props.style]; return ( React.createElement(RCTSlider,babelHelpers.extends({}, props,{ style:style, onValueChange:onValueChange, onSlidingComplete:onSlidingComplete})));}}); var styles=StyleSheet.create({ slider:{ height:40}}); var RCTSlider=requireNativeComponent('RCTSlider',SliderIOS); module.exports=SliderIOS; }); __d('SnapshotViewIOS',function(global, require, module, exports) { 'use strict'; var Platform=require('Platform'); var React=require('React'); var StyleSheet=require('StyleSheet');var _require= require('NativeModules');var TestModule=_require.TestModule;var UIManager=_require.UIManager; var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var SnapshotViewIOS=React.createClass({displayName:'SnapshotViewIOS', onDefaultAction:function(event){ TestModule.verifySnapshot(TestModule.markTestPassed);}, render:function(){ var testIdentifier=this.props.testIdentifier||'test'; var onSnapshotReady=this.props.onSnapshotReady||this.onDefaultAction; return ( React.createElement(RCTSnapshot,babelHelpers.extends({ style:style.snapshot}, this.props,{ onSnapshotReady:onSnapshotReady, testIdentifier:testIdentifier})));}, propTypes:babelHelpers.extends({}, View.propTypes,{ onSnapshotReady:React.PropTypes.func, testIdentifier:React.PropTypes.string})}); var style=StyleSheet.create({ snapshot:{ flex:1}}); var RCTSnapshot=UIManager.RCTSnapshot? requireNativeComponent('RCTSnapshot',SnapshotViewIOS): View; module.exports=SnapshotViewIOS; }); __d('Switch',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var Platform=require('Platform'); var React=require('React'); var StyleSheet=require('StyleSheet'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var Switch=React.createClass({displayName:'Switch', propTypes:babelHelpers.extends({}, View.propTypes,{ value:React.PropTypes.bool, disabled:React.PropTypes.bool, onValueChange:React.PropTypes.func, testID:React.PropTypes.string, tintColor:React.PropTypes.string, onTintColor:React.PropTypes.string, thumbTintColor:React.PropTypes.string}), getDefaultProps:function(){ return { value:false, disabled:false};}, mixins:[NativeMethodsMixin], _rctSwitch:{}, _onChange:function(event){ this.props.onChange&&this.props.onChange(event); this.props.onValueChange&&this.props.onValueChange(event.nativeEvent.value); if(Platform.OS==='android'){ this._rctSwitch.setNativeProps({on:this.props.value});}else { this._rctSwitch.setNativeProps({value:this.props.value});}}, render:function(){var _this=this; var props=babelHelpers.extends({},this.props); props.onStartShouldSetResponder=function(){return true;}; props.onResponderTerminationRequest=function(){return false;}; if(Platform.OS==='android'){ props.enabled=!this.props.disabled; props.on=this.props.value; props.style=[styles.rctSwitchAndroid,this.props.style];}else if(Platform.OS==='ios'){ props.style=[styles.rctSwitchIOS,this.props.style];} return ( React.createElement(RCTSwitch,babelHelpers.extends({}, props,{ ref:function(ref){_this._rctSwitch=ref;}, onChange:this._onChange})));}}); var styles=StyleSheet.create({ rctSwitchIOS:{ height:31, width:51}, rctSwitchAndroid:{ height:27, width:40}}); if(Platform.OS==='android'){ var RCTSwitch=requireNativeComponent('AndroidSwitch',Switch,{ nativeOnly:{onChange:true,on:true,enabled:true}});}else { var RCTSwitch=requireNativeComponent('RCTSwitch',Switch,{ nativeOnly:{onChange:true}});} module.exports=Switch; }); __d('PullToRefreshViewAndroid',function(global, require, module, exports) { 'use strict'; module.exports=require('UnimplementedView'); }); __d('SwitchAndroid',function(global, require, module, exports) { 'use strict'; module.exports=require('UnimplementedView'); }); __d('SwitchIOS',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var PropTypes=require('ReactPropTypes'); var React=require('React'); var StyleSheet=require('StyleSheet'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var SWITCH='switch'; var SwitchIOS=React.createClass({displayName:'SwitchIOS', mixins:[NativeMethodsMixin], propTypes:babelHelpers.extends({}, View.propTypes,{ value:PropTypes.bool, disabled:PropTypes.bool, onValueChange:PropTypes.func, onTintColor:PropTypes.string, thumbTintColor:PropTypes.string, tintColor:PropTypes.string}), getDefaultProps:function(){ return { value:false, disabled:false};}, _onChange:function(event){ this.refs[SWITCH].setNativeProps({value:this.props.value}); if(this.props.value===event.nativeEvent.value||this.props.disabled){ return;} this.props.onChange&&this.props.onChange(event); this.props.onValueChange&&this.props.onValueChange(event.nativeEvent.value);}, render:function(){ return ( React.createElement(RCTSwitch,babelHelpers.extends({}, this.props,{ ref:SWITCH, onChange:this._onChange, style:[styles.rkSwitch,this.props.style]})));}}); var styles=StyleSheet.create({ rkSwitch:{ height:31, width:51}}); var RCTSwitch=requireNativeComponent('RCTSwitch',SwitchIOS,{ nativeOnly:{onChange:true}}); module.exports=SwitchIOS; }); __d('TabBarIOS',function(global, require, module, exports) { 'use strict'; var React=require('React'); var StyleSheet=require('StyleSheet'); var TabBarItemIOS=require('TabBarItemIOS'); var View=require('View'); var requireNativeComponent=require('requireNativeComponent'); var TabBarIOS=React.createClass({displayName:'TabBarIOS', statics:{ Item:TabBarItemIOS}, propTypes:babelHelpers.extends({}, View.propTypes,{ style:View.propTypes.style, tintColor:React.PropTypes.string, barTintColor:React.PropTypes.string, translucent:React.PropTypes.bool}), render:function(){ return ( React.createElement(RCTTabBar,{ style:[styles.tabGroup,this.props.style], tintColor:this.props.tintColor, barTintColor:this.props.barTintColor, translucent:this.props.translucent!==false}, this.props.children));}}); var styles=StyleSheet.create({ tabGroup:{ flex:1}}); var RCTTabBar=requireNativeComponent('RCTTabBar',TabBarIOS); module.exports=TabBarIOS; }); __d('TabBarItemIOS',function(global, require, module, exports) { 'use strict'; var Image=require('Image'); var React=require('React'); var StaticContainer=require('StaticContainer.react'); var StyleSheet=require('StyleSheet'); var View=require('View'); var resolveAssetSource=require('resolveAssetSource'); var requireNativeComponent=require('requireNativeComponent'); var TabBarItemIOS=React.createClass({displayName:'TabBarItemIOS', propTypes:babelHelpers.extends({}, View.propTypes,{ badge:React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number]), systemIcon:React.PropTypes.oneOf([ 'bookmarks', 'contacts', 'downloads', 'favorites', 'featured', 'history', 'more', 'most-recent', 'most-viewed', 'recents', 'search', 'top-rated']), icon:Image.propTypes.source, selectedIcon:Image.propTypes.source, onPress:React.PropTypes.func, selected:React.PropTypes.bool, style:View.propTypes.style, title:React.PropTypes.string}), getInitialState:function(){ return { hasBeenSelected:false};}, componentWillMount:function(){ if(this.props.selected){ this.setState({hasBeenSelected:true});}}, componentWillReceiveProps:function(nextProps){ if(this.state.hasBeenSelected||nextProps.selected){ this.setState({hasBeenSelected:true});}}, render:function(){ var tabContents=null; if(this.state.hasBeenSelected){ tabContents= React.createElement(StaticContainer,{shouldUpdate:this.props.selected}, this.props.children);}else { tabContents=React.createElement(View,null);} var badge=typeof this.props.badge==='number'? ''+this.props.badge: this.props.badge; return ( React.createElement(RCTTabBarItem,babelHelpers.extends({}, this.props,{ icon:this.props.systemIcon||resolveAssetSource(this.props.icon), selectedIcon:resolveAssetSource(this.props.selectedIcon), badge:badge, style:[styles.tab,this.props.style]}), tabContents));}}); var styles=StyleSheet.create({ tab:{ position:'absolute', top:0, right:0, bottom:0, left:0}}); var RCTTabBarItem=requireNativeComponent('RCTTabBarItem',TabBarItemIOS); module.exports=TabBarItemIOS; }); __d('Text',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var Platform=require('Platform'); var React=require('React'); var ReactInstanceMap=require('ReactInstanceMap'); var ReactNativeViewAttributes=require('ReactNativeViewAttributes'); var StyleSheetPropType=require('StyleSheetPropType'); var TextStylePropTypes=require('TextStylePropTypes'); var Touchable=require('Touchable'); var createReactNativeComponentClass= require('createReactNativeComponentClass'); var merge=require('merge'); var stylePropType=StyleSheetPropType(TextStylePropTypes); var viewConfig={ validAttributes:merge(ReactNativeViewAttributes.UIView,{ isHighlighted:true, numberOfLines:true, allowFontScaling:true}), uiViewClassName:'RCTText'}; var Text=React.createClass({displayName:'Text', mixins:[Touchable.Mixin,NativeMethodsMixin], propTypes:{ numberOfLines:React.PropTypes.number, onLayout:React.PropTypes.func, onPress:React.PropTypes.func, suppressHighlighting:React.PropTypes.bool, style:stylePropType, testID:React.PropTypes.string, allowFontScaling:React.PropTypes.bool}, viewConfig:viewConfig, getInitialState:function(){ return merge(this.touchableGetInitialState(),{ isHighlighted:false});}, getDefaultProps:function(){ return { allowFontScaling:true};}, onStartShouldSetResponder:function(){ var shouldSetFromProps=this.props.onStartShouldSetResponder&& this.props.onStartShouldSetResponder(); return shouldSetFromProps||!!this.props.onPress;}, handleResponderTerminationRequest:function(){ var allowTermination=this.touchableHandleResponderTerminationRequest(); if(allowTermination&&this.props.onResponderTerminationRequest){ allowTermination=this.props.onResponderTerminationRequest();} return allowTermination;}, handleResponderGrant:function(e,dispatchID){ this.touchableHandleResponderGrant(e,dispatchID); this.props.onResponderGrant&& this.props.onResponderGrant.apply(this,arguments);}, handleResponderMove:function(e){ this.touchableHandleResponderMove(e); this.props.onResponderMove&& this.props.onResponderMove.apply(this,arguments);}, handleResponderRelease:function(e){ this.touchableHandleResponderRelease(e); this.props.onResponderRelease&& this.props.onResponderRelease.apply(this,arguments);}, handleResponderTerminate:function(e){ this.touchableHandleResponderTerminate(e); this.props.onResponderTerminate&& this.props.onResponderTerminate.apply(this,arguments);}, touchableHandleActivePressIn:function(){ if(this.props.suppressHighlighting||!this.props.onPress){ return;} this.setState({ isHighlighted:true});}, touchableHandleActivePressOut:function(){ if(this.props.suppressHighlighting||!this.props.onPress){ return;} this.setState({ isHighlighted:false});}, touchableHandlePress:function(){ this.props.onPress&&this.props.onPress();}, touchableGetPressRectOffset:function(){ return PRESS_RECT_OFFSET;}, getChildContext:function(){ return {isInAParentText:true};}, childContextTypes:{ isInAParentText:React.PropTypes.bool}, render:function(){ var props={}; for(var key in this.props){ props[key]=this.props[key];} if(props.accessible!==false){ props.accessible=true;} props.isHighlighted=this.state.isHighlighted; props.onStartShouldSetResponder=this.onStartShouldSetResponder; props.onResponderTerminationRequest= this.handleResponderTerminationRequest; props.onResponderGrant=this.handleResponderGrant; props.onResponderMove=this.handleResponderMove; props.onResponderRelease=this.handleResponderRelease; props.onResponderTerminate=this.handleResponderTerminate; var context=ReactInstanceMap.get(this)._context; if(context.isInAParentText){ return React.createElement(RCTVirtualText,props);}else { return React.createElement(RCTText,props);}}}); var PRESS_RECT_OFFSET={top:20,left:20,right:20,bottom:30}; var RCTText=createReactNativeComponentClass(viewConfig); var RCTVirtualText=RCTText; if(Platform.OS==='android'){ RCTVirtualText=createReactNativeComponentClass({ validAttributes:merge(ReactNativeViewAttributes.UIView,{ isHighlighted:true}), uiViewClassName:'RCTVirtualText'});} module.exports=Text; }); __d('Touchable',function(global, require, module, exports) { 'use strict'; var BoundingDimensions=require('BoundingDimensions'); var Position=require('Position'); var TouchEventUtils=require('TouchEventUtils'); var keyMirror=require('keyMirror'); var queryLayoutByID=require('queryLayoutByID'); var States=keyMirror({ NOT_RESPONDER:null, RESPONDER_INACTIVE_PRESS_IN:null, RESPONDER_INACTIVE_PRESS_OUT:null, RESPONDER_ACTIVE_PRESS_IN:null, RESPONDER_ACTIVE_PRESS_OUT:null, RESPONDER_ACTIVE_LONG_PRESS_IN:null, RESPONDER_ACTIVE_LONG_PRESS_OUT:null, ERROR:null}); var IsActive={ RESPONDER_ACTIVE_PRESS_OUT:true, RESPONDER_ACTIVE_PRESS_IN:true}; var IsPressingIn={ RESPONDER_INACTIVE_PRESS_IN:true, RESPONDER_ACTIVE_PRESS_IN:true, RESPONDER_ACTIVE_LONG_PRESS_IN:true}; var IsLongPressingIn={ RESPONDER_ACTIVE_LONG_PRESS_IN:true}; var Signals=keyMirror({ DELAY:null, RESPONDER_GRANT:null, RESPONDER_RELEASE:null, RESPONDER_TERMINATED:null, ENTER_PRESS_RECT:null, LEAVE_PRESS_RECT:null, LONG_PRESS_DETECTED:null}); var Transitions={ NOT_RESPONDER:{ DELAY:States.ERROR, RESPONDER_GRANT:States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE:States.ERROR, RESPONDER_TERMINATED:States.ERROR, ENTER_PRESS_RECT:States.ERROR, LEAVE_PRESS_RECT:States.ERROR, LONG_PRESS_DETECTED:States.ERROR}, RESPONDER_INACTIVE_PRESS_IN:{ DELAY:States.RESPONDER_ACTIVE_PRESS_IN, RESPONDER_GRANT:States.ERROR, RESPONDER_RELEASE:States.NOT_RESPONDER, RESPONDER_TERMINATED:States.NOT_RESPONDER, ENTER_PRESS_RECT:States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT:States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED:States.ERROR}, RESPONDER_INACTIVE_PRESS_OUT:{ DELAY:States.RESPONDER_ACTIVE_PRESS_OUT, RESPONDER_GRANT:States.ERROR, RESPONDER_RELEASE:States.NOT_RESPONDER, RESPONDER_TERMINATED:States.NOT_RESPONDER, ENTER_PRESS_RECT:States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT:States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED:States.ERROR}, RESPONDER_ACTIVE_PRESS_IN:{ DELAY:States.ERROR, RESPONDER_GRANT:States.ERROR, RESPONDER_RELEASE:States.NOT_RESPONDER, RESPONDER_TERMINATED:States.NOT_RESPONDER, ENTER_PRESS_RECT:States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT:States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED:States.RESPONDER_ACTIVE_LONG_PRESS_IN}, RESPONDER_ACTIVE_PRESS_OUT:{ DELAY:States.ERROR, RESPONDER_GRANT:States.ERROR, RESPONDER_RELEASE:States.NOT_RESPONDER, RESPONDER_TERMINATED:States.NOT_RESPONDER, ENTER_PRESS_RECT:States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT:States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED:States.ERROR}, RESPONDER_ACTIVE_LONG_PRESS_IN:{ DELAY:States.ERROR, RESPONDER_GRANT:States.ERROR, RESPONDER_RELEASE:States.NOT_RESPONDER, RESPONDER_TERMINATED:States.NOT_RESPONDER, ENTER_PRESS_RECT:States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT:States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED:States.RESPONDER_ACTIVE_LONG_PRESS_IN}, RESPONDER_ACTIVE_LONG_PRESS_OUT:{ DELAY:States.ERROR, RESPONDER_GRANT:States.ERROR, RESPONDER_RELEASE:States.NOT_RESPONDER, RESPONDER_TERMINATED:States.NOT_RESPONDER, ENTER_PRESS_RECT:States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT:States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED:States.ERROR}, error:{ DELAY:States.NOT_RESPONDER, RESPONDER_GRANT:States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE:States.NOT_RESPONDER, RESPONDER_TERMINATED:States.NOT_RESPONDER, ENTER_PRESS_RECT:States.NOT_RESPONDER, LEAVE_PRESS_RECT:States.NOT_RESPONDER, LONG_PRESS_DETECTED:States.NOT_RESPONDER}}; var HIGHLIGHT_DELAY_MS=130; var PRESS_EXPAND_PX=20; var LONG_PRESS_THRESHOLD=500; var LONG_PRESS_DELAY_MS=LONG_PRESS_THRESHOLD-HIGHLIGHT_DELAY_MS; var LONG_PRESS_ALLOWED_MOVEMENT=10; var TouchableMixin={ componentWillUnmount:function(){ this.touchableDelayTimeout&&clearTimeout(this.touchableDelayTimeout); this.longPressDelayTimeout&&clearTimeout(this.longPressDelayTimeout); this.pressOutDelayTimeout&&clearTimeout(this.pressOutDelayTimeout);}, touchableGetInitialState:function(){ return { touchable:{touchState:undefined,responderID:null}};}, touchableHandleResponderTerminationRequest:function(){ return !this.props.rejectResponderTermination;}, touchableHandleStartShouldSetResponder:function(){ return true;}, touchableLongPressCancelsPress:function(){ return true;}, touchableHandleResponderGrant:function(e,dispatchID){ e.persist(); this.pressOutDelayTimeout&&clearTimeout(this.pressOutDelayTimeout); this.pressOutDelayTimeout=null; this.state.touchable.touchState=States.NOT_RESPONDER; this.state.touchable.responderID=dispatchID; this._receiveSignal(Signals.RESPONDER_GRANT,e); var delayMS= this.touchableGetHighlightDelayMS!==undefined? Math.max(this.touchableGetHighlightDelayMS(),0):HIGHLIGHT_DELAY_MS; delayMS=isNaN(delayMS)?HIGHLIGHT_DELAY_MS:delayMS; if(delayMS!==0){ this.touchableDelayTimeout=setTimeout( this._handleDelay.bind(this,e), delayMS);}else { this._handleDelay(e);} var longDelayMS= this.touchableGetLongPressDelayMS!==undefined? Math.max(this.touchableGetLongPressDelayMS(),10):LONG_PRESS_DELAY_MS; longDelayMS=isNaN(longDelayMS)?LONG_PRESS_DELAY_MS:longDelayMS; this.longPressDelayTimeout=setTimeout( this._handleLongDelay.bind(this,e), longDelayMS+delayMS);}, touchableHandleResponderRelease:function(e){ this._receiveSignal(Signals.RESPONDER_RELEASE,e);}, touchableHandleResponderTerminate:function(e){ this._receiveSignal(Signals.RESPONDER_TERMINATED,e);}, touchableHandleResponderMove:function(e){ if(this.state.touchable.touchState===States.RESPONDER_INACTIVE_PRESS_IN){ return;} if(!this.state.touchable.positionOnActivate){ return;} var positionOnActivate=this.state.touchable.positionOnActivate; var dimensionsOnActivate=this.state.touchable.dimensionsOnActivate; var pressRectOffset=this.touchableGetPressRectOffset? this.touchableGetPressRectOffset():{ left:PRESS_EXPAND_PX, right:PRESS_EXPAND_PX, top:PRESS_EXPAND_PX, bottom:PRESS_EXPAND_PX}; var pressExpandLeft=pressRectOffset.left; var pressExpandTop=pressRectOffset.top; var pressExpandRight=pressRectOffset.right; var pressExpandBottom=pressRectOffset.bottom; var touch=TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX=touch&&touch.pageX; var pageY=touch&&touch.pageY; if(this.pressInLocation){ var movedDistance=this._getDistanceBetweenPoints(pageX,pageY,this.pressInLocation.pageX,this.pressInLocation.pageY); if(movedDistance>LONG_PRESS_ALLOWED_MOVEMENT){ this._cancelLongPressDelayTimeout();}} var isTouchWithinActive= pageX>positionOnActivate.left-pressExpandLeft&& pageY>positionOnActivate.top-pressExpandTop&& pageX< positionOnActivate.left+ dimensionsOnActivate.width+ pressExpandRight&& pageY< positionOnActivate.top+ dimensionsOnActivate.height+ pressExpandBottom; if(isTouchWithinActive){ this._receiveSignal(Signals.ENTER_PRESS_RECT,e);}else { this._cancelLongPressDelayTimeout(); this._receiveSignal(Signals.LEAVE_PRESS_RECT,e);}}, _remeasureMetricsOnActivation:function(){ queryLayoutByID( this.state.touchable.responderID, null, this._handleQueryLayout);}, _handleQueryLayout:function(l,t,w,h,globalX,globalY){ this.state.touchable.positionOnActivate&& Position.release(this.state.touchable.positionOnActivate); this.state.touchable.dimensionsOnActivate&& BoundingDimensions.release(this.state.touchable.dimensionsOnActivate); this.state.touchable.positionOnActivate=Position.getPooled(globalX,globalY); this.state.touchable.dimensionsOnActivate=BoundingDimensions.getPooled(w,h);}, _handleDelay:function(e){ this.touchableDelayTimeout=null; this._receiveSignal(Signals.DELAY,e);}, _handleLongDelay:function(e){ this.longPressDelayTimeout=null; this._receiveSignal(Signals.LONG_PRESS_DETECTED,e);}, _receiveSignal:function(signal,e){ var curState=this.state.touchable.touchState; if(!(Transitions[curState]&&Transitions[curState][signal])){ throw new Error( 'Unrecognized signal `'+signal+'` or state `'+curState+ '` for Touchable responder `'+this.state.touchable.responderID+'`');} var nextState=Transitions[curState][signal]; if(nextState===States.ERROR){ throw new Error( 'Touchable cannot transition from `'+curState+'` to `'+signal+ '` for responder `'+this.state.touchable.responderID+'`');} if(curState!==nextState){ this._performSideEffectsForTransition(curState,nextState,signal,e); this.state.touchable.touchState=nextState;}}, _cancelLongPressDelayTimeout:function(){ this.longPressDelayTimeout&&clearTimeout(this.longPressDelayTimeout); this.longPressDelayTimeout=null;}, _isHighlight:function(state){ return state===States.RESPONDER_ACTIVE_PRESS_IN|| state===States.RESPONDER_ACTIVE_LONG_PRESS_IN;}, _savePressInLocation:function(e){ var touch=TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX=touch&&touch.pageX; var pageY=touch&&touch.pageY; this.pressInLocation={pageX:pageX,pageY:pageY};}, _getDistanceBetweenPoints:function(aX,aY,bX,bY){ var deltaX=aX-bX; var deltaY=aY-bY; return Math.sqrt(deltaX*deltaX+deltaY*deltaY);}, _performSideEffectsForTransition:function(curState,nextState,signal,e){ var curIsHighlight=this._isHighlight(curState); var newIsHighlight=this._isHighlight(nextState); var isFinalSignal= signal===Signals.RESPONDER_TERMINATED|| signal===Signals.RESPONDER_RELEASE; if(isFinalSignal){ this._cancelLongPressDelayTimeout();} if(!IsActive[curState]&&IsActive[nextState]){ this._remeasureMetricsOnActivation();} if(IsPressingIn[curState]&&signal===Signals.LONG_PRESS_DETECTED){ this.touchableHandleLongPress&&this.touchableHandleLongPress(e);} if(newIsHighlight&&!curIsHighlight){ this._savePressInLocation(e); this.touchableHandleActivePressIn&&this.touchableHandleActivePressIn(e);}else if(!newIsHighlight&&curIsHighlight&&this.touchableHandleActivePressOut){ if(this.touchableGetPressOutDelayMS&&this.touchableGetPressOutDelayMS()){ this.pressOutDelayTimeout=this.setTimeout(function(){ this.touchableHandleActivePressOut(e);}, this.touchableGetPressOutDelayMS());}else { this.touchableHandleActivePressOut(e);}} if(IsPressingIn[curState]&&signal===Signals.RESPONDER_RELEASE){ var hasLongPressHandler=!!this.props.onLongPress; var pressIsLongButStillCallOnPress= IsLongPressingIn[curState]&&( !hasLongPressHandler|| !this.touchableLongPressCancelsPress()); var shouldInvokePress=!IsLongPressingIn[curState]||pressIsLongButStillCallOnPress; if(shouldInvokePress&&this.touchableHandlePress){ this.touchableHandlePress(e);}} this.touchableDelayTimeout&&clearTimeout(this.touchableDelayTimeout); this.touchableDelayTimeout=null;}}; var Touchable={ Mixin:TouchableMixin}; module.exports=Touchable; }); __d('BoundingDimensions',function(global, require, module, exports) { "use strict"; var PooledClass=require('PooledClass'); var twoArgumentPooler=PooledClass.twoArgumentPooler; function BoundingDimensions(width,height){ this.width=width; this.height=height;} BoundingDimensions.prototype.destructor=function(){ this.width=null; this.height=null;}; BoundingDimensions.getPooledFromElement=function(element){ return BoundingDimensions.getPooled( element.offsetWidth, element.offsetHeight);}; PooledClass.addPoolingTo(BoundingDimensions,twoArgumentPooler); module.exports=BoundingDimensions; }); __d('Position',function(global, require, module, exports) { "use strict"; var PooledClass=require('PooledClass'); var twoArgumentPooler=PooledClass.twoArgumentPooler; function Position(left,top){ this.left=left; this.top=top;} Position.prototype.destructor=function(){ this.left=null; this.top=null;}; PooledClass.addPoolingTo(Position,twoArgumentPooler); module.exports=Position; }); __d('TouchEventUtils',function(global, require, module, exports) { var TouchEventUtils={ extractSingleTouch:function(nativeEvent){ var touches=nativeEvent.touches; var changedTouches=nativeEvent.changedTouches; var hasTouches=touches&&touches.length>0; var hasChangedTouches=changedTouches&&changedTouches.length>0; return !hasTouches&&hasChangedTouches?changedTouches[0]: hasTouches?touches[0]: nativeEvent;}}; module.exports=TouchEventUtils; }); __d('queryLayoutByID',function(global, require, module, exports) { 'use strict'; var ReactNativeTagHandles=require('ReactNativeTagHandles'); var RCTUIManager=require('NativeModules').UIManager; var queryLayoutByID=function( rootNodeID, onError, onSuccess) { RCTUIManager.measure( ReactNativeTagHandles.rootNodeIDToTag[rootNodeID], onSuccess);}; module.exports=queryLayoutByID; }); __d('TextInput',function(global, require, module, exports) { 'use strict'; var DocumentSelectionState=require('DocumentSelectionState'); var EventEmitter=require('EventEmitter'); var NativeMethodsMixin=require('NativeMethodsMixin'); var Platform=require('Platform'); var PropTypes=require('ReactPropTypes'); var RCTUIManager=require('NativeModules').UIManager; var React=require('React'); var ReactChildren=require('ReactChildren'); var StyleSheet=require('StyleSheet'); var Text=require('Text'); var TextInputState=require('TextInputState'); var TimerMixin=require('react-timer-mixin/TimerMixin.js'); var TouchableWithoutFeedback=require('TouchableWithoutFeedback'); var View=require('View'); var createReactNativeComponentClass=require('createReactNativeComponentClass'); var emptyFunction=require('emptyFunction'); var invariant=require('invariant'); var requireNativeComponent=require('requireNativeComponent'); var onlyMultiline={ onTextInput:true, children:true}; var notMultiline={ onSubmitEditing:true}; if(Platform.OS==='android'){ var AndroidTextInput=requireNativeComponent('AndroidTextInput',null);}else if(Platform.OS==='ios'){ var RCTTextView=requireNativeComponent('RCTTextView',null); var RCTTextField=requireNativeComponent('RCTTextField',null);} var TextInput=React.createClass({displayName:'TextInput', statics:{ State:TextInputState}, propTypes:babelHelpers.extends({}, View.propTypes,{ autoCapitalize:PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters']), autoCorrect:PropTypes.bool, autoFocus:PropTypes.bool, textAlign:PropTypes.oneOf([ 'start', 'center', 'end']), textAlignVertical:PropTypes.oneOf([ 'top', 'center', 'bottom']), editable:PropTypes.bool, keyboardType:PropTypes.oneOf([ 'default', 'numeric', 'email-address', 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'phone-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search']), keyboardAppearance:PropTypes.oneOf([ 'default', 'light', 'dark']), returnKeyType:PropTypes.oneOf([ 'default', 'go', 'google', 'join', 'next', 'route', 'search', 'send', 'yahoo', 'done', 'emergency-call']), maxLength:PropTypes.number, numberOfLines:PropTypes.number, enablesReturnKeyAutomatically:PropTypes.bool, multiline:PropTypes.bool, onBlur:PropTypes.func, onFocus:PropTypes.func, onChange:PropTypes.func, onChangeText:PropTypes.func, onEndEditing:PropTypes.func, onSubmitEditing:PropTypes.func, onKeyPress:PropTypes.func, onLayout:PropTypes.func, placeholder:PropTypes.string, placeholderTextColor:PropTypes.string, secureTextEntry:PropTypes.bool, selectionState:PropTypes.instanceOf(DocumentSelectionState), value:PropTypes.string, defaultValue:PropTypes.string, clearButtonMode:PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always']), clearTextOnFocus:PropTypes.bool, selectTextOnFocus:PropTypes.bool, blurOnSubmit:PropTypes.bool, style:Text.propTypes.style, testID:PropTypes.string, underlineColorAndroid:PropTypes.string}), getDefaultProps:function(){ return { blurOnSubmit:true};}, mixins:[NativeMethodsMixin,TimerMixin], viewConfig:Platform.OS==='ios'?RCTTextField.viewConfig: Platform.OS==='android'?AndroidTextInput.viewConfig:{}, isFocused:function(){ return TextInputState.currentlyFocusedField()=== React.findNodeHandle(this.refs.input);}, getInitialState:function(){ return { mostRecentEventCount:0};}, contextTypes:{ onFocusRequested:React.PropTypes.func, focusEmitter:React.PropTypes.instanceOf(EventEmitter)}, _focusSubscription:undefined, componentDidMount:function(){var _this=this; if(!this.context.focusEmitter){ if(this.props.autoFocus){ this.requestAnimationFrame(this.focus);} return;} this._focusSubscription=this.context.focusEmitter.addListener( 'focus', function(el){ if(_this===el){ _this.requestAnimationFrame(_this.focus);}else if(_this.isFocused()){ _this.blur();}}); if(this.props.autoFocus){ this.context.onFocusRequested(this);}}, componentWillUnmount:function(){ this._focusSubscription&&this._focusSubscription.remove(); if(this.isFocused()){ this.blur();}}, getChildContext:function(){ return {isInAParentText:true};}, childContextTypes:{ isInAParentText:React.PropTypes.bool}, clear:function(){ this.setNativeProps({text:''});}, render:function(){ if(Platform.OS==='ios'){ return this._renderIOS();}else if(Platform.OS==='android'){ return this._renderAndroid();}}, _getText:function(){ return typeof this.props.value==='string'? this.props.value: this.props.defaultValue;}, _renderIOS:function(){var _this2=this; var textContainer; var onSelectionChange; if(this.props.selectionState||this.props.onSelectionChange){ onSelectionChange=function(event){ if(_this2.props.selectionState){ var selection=event.nativeEvent.selection; _this2.props.selectionState.update(selection.start,selection.end);} _this2.props.onSelectionChange&&_this2.props.onSelectionChange(event);};} var props=babelHelpers.extends({},this.props); props.style=[styles.input,this.props.style]; if(!props.multiline){ for(var propKey in onlyMultiline){ if(props[propKey]){ throw new Error( 'TextInput prop `'+propKey+'` is only supported with multiline.');}} textContainer= React.createElement(RCTTextField,babelHelpers.extends({ ref:'input'}, props,{ onFocus:this._onFocus, onBlur:this._onBlur, onChange:this._onChange, onSelectionChange:onSelectionChange, onSelectionChangeShouldSetResponder:emptyFunction.thatReturnsTrue, text:this._getText(), mostRecentEventCount:this.state.mostRecentEventCount}));}else { for(var propKey in notMultiline){ if(props[propKey]){ throw new Error( 'TextInput prop `'+propKey+'` cannot be used with multiline.');}} var children=props.children; var childCount=0; ReactChildren.forEach(children,function(){return ++childCount;}); invariant( !(props.value&&childCount), 'Cannot specify both value and children.'); if(childCount>1){ children=React.createElement(Text,null,children);} if(props.inputView){ children=[children,props.inputView];} textContainer= React.createElement(RCTTextView,babelHelpers.extends({ ref:'input'}, props,{ children:children, mostRecentEventCount:this.state.mostRecentEventCount, onFocus:this._onFocus, onBlur:this._onBlur, onChange:this._onChange, onSelectionChange:onSelectionChange, onTextInput:this._onTextInput, onSelectionChangeShouldSetResponder:emptyFunction.thatReturnsTrue, text:this._getText()}));} return ( React.createElement(TouchableWithoutFeedback,{ onPress:this._onPress, rejectResponderTermination:true, testID:props.testID}, textContainer));}, _renderAndroid:function(){ var autoCapitalize=RCTUIManager.UIText.AutocapitalizationType[this.props.autoCapitalize]; var textAlign= RCTUIManager.AndroidTextInput.Constants.TextAlign[this.props.textAlign]; var textAlignVertical= RCTUIManager.AndroidTextInput.Constants.TextAlignVertical[this.props.textAlignVertical]; var children=this.props.children; var childCount=0; ReactChildren.forEach(children,function(){return ++childCount;}); invariant( !(this.props.value&&childCount), 'Cannot specify both value and children.'); if(childCount>1){ children=React.createElement(Text,null,children);} var textContainer= React.createElement(AndroidTextInput,{ ref:'input', style:[this.props.style], autoCapitalize:autoCapitalize, autoCorrect:this.props.autoCorrect, textAlign:textAlign, textAlignVertical:textAlignVertical, keyboardType:this.props.keyboardType, mostRecentEventCount:this.state.mostRecentEventCount, multiline:this.props.multiline, numberOfLines:this.props.numberOfLines, maxLength:this.props.maxLength, onFocus:this._onFocus, onBlur:this._onBlur, onChange:this._onChange, onTextInput:this._onTextInput, onEndEditing:this.props.onEndEditing, onSubmitEditing:this.props.onSubmitEditing, onLayout:this.props.onLayout, password:this.props.password||this.props.secureTextEntry, placeholder:this.props.placeholder, placeholderTextColor:this.props.placeholderTextColor, text:this._getText(), underlineColorAndroid:this.props.underlineColorAndroid, children:children, editable:this.props.editable}); return ( React.createElement(TouchableWithoutFeedback,{ onPress:this._onPress, testID:this.props.testID}, textContainer));}, _onFocus:function(event){ if(this.props.onFocus){ this.props.onFocus(event);}}, _onPress:function(event){ if(this.props.editable||this.props.editable===undefined){ this.focus();}}, _onChange:function(event){var _this3=this; if(Platform.OS==='android'){ this.refs.input.setNativeProps({ mostRecentEventCount:event.nativeEvent.eventCount});} var text=event.nativeEvent.text; var eventCount=event.nativeEvent.eventCount; this.props.onChange&&this.props.onChange(event); this.props.onChangeText&&this.props.onChangeText(text); this.setState({mostRecentEventCount:eventCount},function(){ if(Platform.OS==='android'){ if(text!==_this3.props.value&&typeof _this3.props.value==='string'){ _this3.refs.input.setNativeProps({ text:_this3.props.value});}}});}, _onBlur:function(event){ this.blur(); if(this.props.onBlur){ this.props.onBlur(event);}}, _onTextInput:function(event){ this.props.onTextInput&&this.props.onTextInput(event);}}); var styles=StyleSheet.create({ input:{ alignSelf:'stretch'}}); module.exports=TextInput; }); __d('DocumentSelectionState',function(global, require, module, exports) { var mixInEventEmitter=require('mixInEventEmitter');var DocumentSelectionState=(function(){ function DocumentSelectionState(anchor,focus){babelHelpers.classCallCheck(this,DocumentSelectionState); this._anchorOffset=anchor; this._focusOffset=focus; this._hasFocus=false;}babelHelpers.createClass(DocumentSelectionState,[{key:'update',value:function update( anchor,focus){ if(this._anchorOffset!==anchor||this._focusOffset!==focus){ this._anchorOffset=anchor; this._focusOffset=focus; this.emit('update');}}},{key:'constrainLength',value:function constrainLength( maxLength){ this.update( Math.min(this._anchorOffset,maxLength), Math.min(this._focusOffset,maxLength));}},{key:'focus',value:function focus() { if(!this._hasFocus){ this._hasFocus=true; this.emit('focus');}}},{key:'blur',value:function blur() { if(this._hasFocus){ this._hasFocus=false; this.emit('blur');}}},{key:'hasFocus',value:function hasFocus() { return this._hasFocus;}},{key:'isCollapsed',value:function isCollapsed() { return this._anchorOffset===this._focusOffset;}},{key:'isBackward',value:function isBackward() { return this._anchorOffset>this._focusOffset;}},{key:'getAnchorOffset',value:function getAnchorOffset() { return this._hasFocus?this._anchorOffset:null;}},{key:'getFocusOffset',value:function getFocusOffset() { return this._hasFocus?this._focusOffset:null;}},{key:'getStartOffset',value:function getStartOffset() { return ( this._hasFocus?Math.min(this._anchorOffset,this._focusOffset):null);}},{key:'getEndOffset',value:function getEndOffset() { return ( this._hasFocus?Math.max(this._anchorOffset,this._focusOffset):null);}},{key:'overlaps',value:function overlaps( start,end){ return ( this.hasFocus()&& this.getStartOffset()<=end&&start<=this.getEndOffset());}}]);return DocumentSelectionState;})(); mixInEventEmitter(DocumentSelectionState,{ 'blur':true, 'focus':true, 'update':true}); module.exports=DocumentSelectionState; }); __d('mixInEventEmitter',function(global, require, module, exports) { var EventEmitter=require('EventEmitter'); var EventEmitterWithHolding=require('EventEmitterWithHolding'); var EventHolder=require('EventHolder'); var EventValidator=require('EventValidator'); var copyProperties=require('copyProperties'); var invariant=require('invariant'); var keyOf=require('keyOf'); var TYPES_KEY=keyOf({__types:true}); function mixInEventEmitter(klass,types){ invariant(types,'Must supply set of valid event types'); invariant(!this.__eventEmitter,'An active emitter is already mixed in'); var target=klass.prototype||klass; var ctor=klass.constructor; if(ctor){ invariant( ctor===Object||ctor===Function, 'Mix EventEmitter into a class, not an instance');} if(target.hasOwnProperty(TYPES_KEY)){ copyProperties(target.__types,types);}else if(target.__types){ target.__types=copyProperties({},target.__types,types);}else { target.__types=types;} copyProperties(target,EventEmitterMixin);} var EventEmitterMixin={ emit:function(eventType,a,b,c,d,e,_){ return this.__getEventEmitter().emit(eventType,a,b,c,d,e,_);}, emitAndHold:function(eventType,a,b,c,d,e,_){ return this.__getEventEmitter().emitAndHold(eventType,a,b,c,d,e,_);}, addListener:function(eventType,listener,context){ return this.__getEventEmitter().addListener(eventType,listener,context);}, once:function(eventType,listener,context){ return this.__getEventEmitter().once(eventType,listener,context);}, addRetroactiveListener:function(eventType,listener,context){ return this.__getEventEmitter().addRetroactiveListener( eventType, listener, context);}, addListenerMap:function(listenerMap,context){ return this.__getEventEmitter().addListenerMap(listenerMap,context);}, addRetroactiveListenerMap:function(listenerMap,context){ return this.__getEventEmitter().addListenerMap(listenerMap,context);}, removeAllListeners:function(){ this.__getEventEmitter().removeAllListeners();}, removeCurrentListener:function(){ this.__getEventEmitter().removeCurrentListener();}, releaseHeldEventType:function(eventType){ this.__getEventEmitter().releaseHeldEventType(eventType);}, __getEventEmitter:function(){ if(!this.__eventEmitter){ var emitter=new EventEmitter(); emitter=EventValidator.addValidation(emitter,this.__types); var holder=new EventHolder(); this.__eventEmitter=new EventEmitterWithHolding(emitter,holder);} return this.__eventEmitter;}}; module.exports=mixInEventEmitter; }); __d('EventEmitterWithHolding',function(global, require, module, exports) { 'use strict';var EventEmitterWithHolding=(function(){ function EventEmitterWithHolding(emitter,holder){babelHelpers.classCallCheck(this,EventEmitterWithHolding); this._emitter=emitter; this._eventHolder=holder; this._currentEventToken=null; this._emittingHeldEvents=false;}babelHelpers.createClass(EventEmitterWithHolding,[{key:'addListener',value:function addListener( eventType,listener,context){ return this._emitter.addListener(eventType,listener,context);}},{key:'once',value:function once( eventType,listener,context){ return this._emitter.once(eventType,listener,context);}},{key:'addRetroactiveListener',value:function addRetroactiveListener( eventType,listener,context){ var subscription=this._emitter.addListener(eventType,listener,context); this._emittingHeldEvents=true; this._eventHolder.emitToListener(eventType,listener,context); this._emittingHeldEvents=false; return subscription;}},{key:'removeAllListeners',value:function removeAllListeners( eventType){ this._emitter.removeAllListeners(eventType);}},{key:'removeCurrentListener',value:function removeCurrentListener() { this._emitter.removeCurrentListener();}},{key:'listeners',value:function listeners( eventType){ return this._emitter.listeners(eventType);}},{key:'emit',value:function emit( eventType,a,b,c,d,e,_){ this._emitter.emit(eventType,a,b,c,d,e,_);}},{key:'emitAndHold',value:function emitAndHold( eventType,a,b,c,d,e,_){ this._currentEventToken=this._eventHolder.holdEvent( eventType, a,b,c,d,e,_); this._emitter.emit(eventType,a,b,c,d,e,_); this._currentEventToken=null;}},{key:'releaseCurrentEvent',value:function releaseCurrentEvent() { if(this._currentEventToken!==null){ this._eventHolder.releaseEvent(this._currentEventToken);}else if(this._emittingHeldEvents){ this._eventHolder.releaseCurrentEvent();}}},{key:'releaseHeldEventType',value:function releaseHeldEventType( eventType){ this._eventHolder.releaseEventType(eventType);}}]);return EventEmitterWithHolding;})(); module.exports=EventEmitterWithHolding; }); __d('EventHolder',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant');var EventHolder=(function(){ function EventHolder(){babelHelpers.classCallCheck(this,EventHolder); this._heldEvents={}; this._currentEventKey=null;}babelHelpers.createClass(EventHolder,[{key:'holdEvent',value:function holdEvent( eventType,a,b,c,d,e,_){ this._heldEvents[eventType]=this._heldEvents[eventType]||[]; var eventsOfType=this._heldEvents[eventType]; var key={ eventType:eventType, index:eventsOfType.length}; eventsOfType.push([a,b,c,d,e,_]); return key;}},{key:'emitToListener',value:function emitToListener( eventType,listener,context){var _this=this; var eventsOfType=this._heldEvents[eventType]; if(!eventsOfType){ return;} var origEventKey=this._currentEventKey; eventsOfType.forEach(function(eventHeld,index){ if(!eventHeld){ return;} _this._currentEventKey={ eventType:eventType, index:index}; listener.apply(context,eventHeld);}); this._currentEventKey=origEventKey;}},{key:'releaseCurrentEvent',value:function releaseCurrentEvent() { invariant( this._currentEventKey!==null, 'Not in an emitting cycle; there is no current event'); this.releaseEvent(this._currentEventKey);}},{key:'releaseEvent',value:function releaseEvent( token){ delete this._heldEvents[token.eventType][token.index];}},{key:'releaseEventType',value:function releaseEventType( type){ this._heldEvents[type]=[];}}]);return EventHolder;})(); module.exports=EventHolder; }); __d('EventValidator',function(global, require, module, exports) { 'use strict'; var copyProperties=require('copyProperties'); var EventValidator={ addValidation:function(emitter,types){ var eventTypes=Object.keys(types); var emitterWithValidation=Object.create(emitter); copyProperties(emitterWithValidation,{ emit:function emit(type,a,b,c,d,e,_){ assertAllowsEventType(type,eventTypes); return emitter.emit.call(this,type,a,b,c,d,e,_);}}); return emitterWithValidation;}}; function assertAllowsEventType(type,allowedTypes){ if(allowedTypes.indexOf(type)===-1){ throw new TypeError(errorMessageFor(type,allowedTypes));}} function errorMessageFor(type,allowedTypes){ var message='Unknown event type "'+type+'". '; if(__DEV__){ message+=recommendationFor(type,allowedTypes);} message+='Known event types: '+allowedTypes.join(', ')+'.'; return message;} if(__DEV__){ var recommendationFor=function(type,allowedTypes){ var closestTypeRecommendation=closestTypeFor(type,allowedTypes); if(isCloseEnough(closestTypeRecommendation,type)){ return 'Did you mean "'+closestTypeRecommendation.type+'"? ';}else { return '';}}; var closestTypeFor=function(type,allowedTypes){ var typeRecommendations=allowedTypes.map( typeRecommendationFor.bind(this,type)); return typeRecommendations.sort(recommendationSort)[0];}; var typeRecommendationFor=function(type,recomendedType){ return { type:recomendedType, distance:damerauLevenshteinDistance(type,recomendedType)};}; var recommendationSort=function(recommendationA,recommendationB){ if(recommendationA.distancerecommendationB.distance){ return 1;}else { return 0;}}; var isCloseEnough=function(closestType,actualType){ return closestType.distance/actualType.length<0.334;}; var damerauLevenshteinDistance=function(a,b){ var i,j; var d=[]; for(i=0;i<=a.length;i++){ d[i]=[i];} for(j=1;j<=b.length;j++){ d[0][j]=j;} for(i=1;i<=a.length;i++){ for(j=1;j<=b.length;j++){ var cost=a.charAt(i-1)===b.charAt(j-1)?0:1; d[i][j]=Math.min( d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+cost); if(i>1&&j>1&& a.charAt(i-1)==b.charAt(j-2)&& a.charAt(i-2)==b.charAt(j-1)){ d[i][j]=Math.min(d[i][j],d[i-2][j-2]+cost);}}} return d[a.length][b.length];};} module.exports=EventValidator; }); __d('copyProperties',function(global, require, module, exports) { function copyProperties(obj,a,b,c,d,e,f){ obj=obj||{}; if(__DEV__){ if(f){ throw new Error('Too many arguments passed to copyProperties');}} var args=[a,b,c,d,e]; var ii=0,v; while(args[ii]){ v=args[ii++]; for(var k in v){ obj[k]=v[k];} if(v.hasOwnProperty&&v.hasOwnProperty('toString')&& typeof v.toString!='undefined'&&obj.toString!==v.toString){ obj.toString=v.toString;}} return obj;} module.exports=copyProperties; }); __d('TouchableWithoutFeedback',function(global, require, module, exports) { 'use strict'; var EdgeInsetsPropType=require('EdgeInsetsPropType'); var React=require('React'); var TimerMixin=require('react-timer-mixin/TimerMixin.js'); var Touchable=require('Touchable'); var View=require('View'); var ensurePositiveDelayProps=require('ensurePositiveDelayProps'); var invariant=require('invariant'); var onlyChild=require('onlyChild'); var PRESS_RETENTION_OFFSET={top:20,left:20,right:20,bottom:30}; var TouchableWithoutFeedback=React.createClass({displayName:'TouchableWithoutFeedback', mixins:[TimerMixin,Touchable.Mixin], propTypes:{ accessible:React.PropTypes.bool, accessibilityComponentType:React.PropTypes.oneOf(View.AccessibilityComponentType), accessibilityTraits:React.PropTypes.oneOfType([ React.PropTypes.oneOf(View.AccessibilityTraits), React.PropTypes.arrayOf(React.PropTypes.oneOf(View.AccessibilityTraits))]), onPress:React.PropTypes.func, onPressIn:React.PropTypes.func, onPressOut:React.PropTypes.func, onLayout:React.PropTypes.func, onLongPress:React.PropTypes.func, delayPressIn:React.PropTypes.number, delayPressOut:React.PropTypes.number, delayLongPress:React.PropTypes.number, pressRetentionOffset:EdgeInsetsPropType}, getInitialState:function(){ return this.touchableGetInitialState();}, componentDidMount:function(){ ensurePositiveDelayProps(this.props);}, componentWillReceiveProps:function(nextProps){ ensurePositiveDelayProps(nextProps);}, touchableHandlePress:function(e){ this.props.onPress&&this.props.onPress(e);}, touchableHandleActivePressIn:function(e){ this.props.onPressIn&&this.props.onPressIn(e);}, touchableHandleActivePressOut:function(e){ this.props.onPressOut&&this.props.onPressOut(e);}, touchableHandleLongPress:function(e){ this.props.onLongPress&&this.props.onLongPress(e);}, touchableGetPressRectOffset:function(){ return this.props.pressRetentionOffset||PRESS_RETENTION_OFFSET;}, touchableGetHighlightDelayMS:function(){ return this.props.delayPressIn||0;}, touchableGetLongPressDelayMS:function(){ return this.props.delayLongPress===0?0: this.props.delayLongPress||500;}, touchableGetPressOutDelayMS:function(){ return this.props.delayPressOut||0;}, render:function(){ return React.cloneElement(onlyChild(this.props.children),{ accessible:this.props.accessible!==false, accessibilityComponentType:this.props.accessibilityComponentType, accessibilityTraits:this.props.accessibilityTraits, testID:this.props.testID, onLayout:this.props.onLayout, onStartShouldSetResponder:this.touchableHandleStartShouldSetResponder, onResponderTerminationRequest:this.touchableHandleResponderTerminationRequest, onResponderGrant:this.touchableHandleResponderGrant, onResponderMove:this.touchableHandleResponderMove, onResponderRelease:this.touchableHandleResponderRelease, onResponderTerminate:this.touchableHandleResponderTerminate});}}); module.exports=TouchableWithoutFeedback; }); __d('ensurePositiveDelayProps',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var ensurePositiveDelayProps=function(props){ invariant( !(props.delayPressIn<0||props.delayPressOut<0|| props.delayLongPress<0), 'Touchable components cannot have negative delay properties');}; module.exports=ensurePositiveDelayProps; }); __d('ToastAndroid',function(global, require, module, exports) { 'use strict'; var warning=require('warning'); var ToastAndroid={ show:function( message, duration) { warning(false,'Cannot use ToastAndroid on iOS.');}}; module.exports=ToastAndroid; }); __d('ToolbarAndroid',function(global, require, module, exports) { 'use strict'; module.exports=require('UnimplementedView'); }); __d('TouchableHighlight',function(global, require, module, exports) { 'use strict'; var NativeMethodsMixin=require('NativeMethodsMixin'); var React=require('React'); var ReactNativeViewAttributes=require('ReactNativeViewAttributes'); var StyleSheet=require('StyleSheet'); var TimerMixin=require('react-timer-mixin/TimerMixin.js'); var Touchable=require('Touchable'); var TouchableWithoutFeedback=require('TouchableWithoutFeedback'); var View=require('View'); var ensureComponentIsNative=require('ensureComponentIsNative'); var ensurePositiveDelayProps=require('ensurePositiveDelayProps'); var keyOf=require('keyOf'); var merge=require('merge'); var onlyChild=require('onlyChild'); var DEFAULT_PROPS={ activeOpacity:0.8, underlayColor:'black'}; var PRESS_RETENTION_OFFSET={top:20,left:20,right:20,bottom:30}; var TouchableHighlight=React.createClass({displayName:'TouchableHighlight', propTypes:babelHelpers.extends({}, TouchableWithoutFeedback.propTypes,{ activeOpacity:React.PropTypes.number, underlayColor:React.PropTypes.string, style:View.propTypes.style, onShowUnderlay:React.PropTypes.func, onHideUnderlay:React.PropTypes.func}), mixins:[NativeMethodsMixin,TimerMixin,Touchable.Mixin], getDefaultProps:function(){return DEFAULT_PROPS;}, computeSyntheticState:function(props){ return { activeProps:{ style:{ opacity:props.activeOpacity}}, activeUnderlayProps:{ style:{ backgroundColor:props.underlayColor}}, underlayStyle:[ INACTIVE_UNDERLAY_PROPS.style, props.style]};}, getInitialState:function(){ return merge( this.touchableGetInitialState(),this.computeSyntheticState(this.props));}, componentDidMount:function(){ ensurePositiveDelayProps(this.props); ensureComponentIsNative(this.refs[CHILD_REF]);}, componentDidUpdate:function(){ ensureComponentIsNative(this.refs[CHILD_REF]);}, componentWillReceiveProps:function(nextProps){ ensurePositiveDelayProps(nextProps); if(nextProps.activeOpacity!==this.props.activeOpacity|| nextProps.underlayColor!==this.props.underlayColor|| nextProps.style!==this.props.style){ this.setState(this.computeSyntheticState(nextProps));}}, viewConfig:{ uiViewClassName:'RCTView', validAttributes:ReactNativeViewAttributes.RCTView}, touchableHandleActivePressIn:function(e){ this.clearTimeout(this._hideTimeout); this._hideTimeout=null; this._showUnderlay(); this.props.onPressIn&&this.props.onPressIn(e);}, touchableHandleActivePressOut:function(e){ if(!this._hideTimeout){ this._hideUnderlay();} this.props.onPressOut&&this.props.onPressOut(e);}, touchableHandlePress:function(e){ this.clearTimeout(this._hideTimeout); this._showUnderlay(); this._hideTimeout=this.setTimeout(this._hideUnderlay, this.props.delayPressOut||100); this.props.onPress&&this.props.onPress(e);}, touchableHandleLongPress:function(e){ this.props.onLongPress&&this.props.onLongPress(e);}, touchableGetPressRectOffset:function(){ return this.props.pressRetentionOffset||PRESS_RETENTION_OFFSET;}, touchableGetHighlightDelayMS:function(){ return this.props.delayPressIn;}, touchableGetLongPressDelayMS:function(){ return this.props.delayLongPress;}, touchableGetPressOutDelayMS:function(){ return this.props.delayPressOut;}, _showUnderlay:function(){ if(!this.isMounted()){ return;} this.refs[UNDERLAY_REF].setNativeProps(this.state.activeUnderlayProps); this.refs[CHILD_REF].setNativeProps(this.state.activeProps); this.props.onShowUnderlay&&this.props.onShowUnderlay();}, _hideUnderlay:function(){ this.clearTimeout(this._hideTimeout); this._hideTimeout=null; if(this.refs[UNDERLAY_REF]){ this.refs[CHILD_REF].setNativeProps(INACTIVE_CHILD_PROPS); this.refs[UNDERLAY_REF].setNativeProps(babelHelpers.extends({}, INACTIVE_UNDERLAY_PROPS,{ style:this.state.underlayStyle})); this.props.onHideUnderlay&&this.props.onHideUnderlay();}}, render:function(){ return ( React.createElement(View,{ accessible:true, accessibilityComponentType:this.props.accessibilityComponentType, accessibilityTraits:this.props.accessibilityTraits, ref:UNDERLAY_REF, style:this.state.underlayStyle, onLayout:this.props.onLayout, onStartShouldSetResponder:this.touchableHandleStartShouldSetResponder, onResponderTerminationRequest:this.touchableHandleResponderTerminationRequest, onResponderGrant:this.touchableHandleResponderGrant, onResponderMove:this.touchableHandleResponderMove, onResponderRelease:this.touchableHandleResponderRelease, onResponderTerminate:this.touchableHandleResponderTerminate, testID:this.props.testID}, React.cloneElement( onlyChild(this.props.children), { ref:CHILD_REF})));}}); var CHILD_REF=keyOf({childRef:null}); var UNDERLAY_REF=keyOf({underlayRef:null}); var INACTIVE_CHILD_PROPS={ style:StyleSheet.create({x:{opacity:1.0}}).x}; var INACTIVE_UNDERLAY_PROPS={ style:StyleSheet.create({x:{backgroundColor:'transparent'}}).x}; module.exports=TouchableHighlight; }); __d('ensureComponentIsNative',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var ensureComponentIsNative=function(component){ invariant( component&&typeof component.setNativeProps==='function', 'Touchable child must either be native or forward setNativeProps to a '+ 'native component');}; module.exports=ensureComponentIsNative; }); __d('TouchableNativeFeedback',function(global, require, module, exports) { 'use strict'; var React=require('React'); var StyleSheet=require('StyleSheet'); var Text=require('Text'); var View=require('View'); var DummyTouchableNativeFeedback=React.createClass({displayName:'DummyTouchableNativeFeedback', render:function(){ return ( React.createElement(View,{style:[styles.container,this.props.style]}, React.createElement(Text,{style:styles.info},'TouchableNativeFeedback is not supported on this platform!')));}}); var styles=StyleSheet.create({ container:{ height:100, width:300, backgroundColor:'#ffbcbc', borderWidth:1, borderColor:'red', alignItems:'center', justifyContent:'center', margin:10}, info:{ color:'#333333', margin:20}}); module.exports=DummyTouchableNativeFeedback; }); __d('TouchableOpacity',function(global, require, module, exports) { 'use strict'; var Animated=require('Animated'); var NativeMethodsMixin=require('NativeMethodsMixin'); var React=require('React'); var TimerMixin=require('react-timer-mixin/TimerMixin.js'); var Touchable=require('Touchable'); var TouchableWithoutFeedback=require('TouchableWithoutFeedback'); var ensurePositiveDelayProps=require('ensurePositiveDelayProps'); var flattenStyle=require('flattenStyle'); var PRESS_RETENTION_OFFSET={top:20,left:20,right:20,bottom:30}; var TouchableOpacity=React.createClass({displayName:'TouchableOpacity', mixins:[TimerMixin,Touchable.Mixin,NativeMethodsMixin], propTypes:babelHelpers.extends({}, TouchableWithoutFeedback.propTypes,{ activeOpacity:React.PropTypes.number}), getDefaultProps:function(){ return { activeOpacity:0.2};}, getInitialState:function(){ return babelHelpers.extends({}, this.touchableGetInitialState(),{ anim:new Animated.Value(1)});}, componentDidMount:function(){ ensurePositiveDelayProps(this.props);}, componentWillReceiveProps:function(nextProps){ ensurePositiveDelayProps(nextProps);}, setOpacityTo:function(value){ Animated.timing( this.state.anim, {toValue:value,duration:150}). start();}, touchableHandleActivePressIn:function(e){ this.clearTimeout(this._hideTimeout); this._hideTimeout=null; this._opacityActive(); this.props.onPressIn&&this.props.onPressIn(e);}, touchableHandleActivePressOut:function(e){ if(!this._hideTimeout){ this._opacityInactive();} this.props.onPressOut&&this.props.onPressOut(e);}, touchableHandlePress:function(e){ this.clearTimeout(this._hideTimeout); this._opacityActive(); this._hideTimeout=this.setTimeout( this._opacityInactive, this.props.delayPressOut||100); this.props.onPress&&this.props.onPress(e);}, touchableHandleLongPress:function(e){ this.props.onLongPress&&this.props.onLongPress(e);}, touchableGetPressRectOffset:function(){ return this.props.pressRetentionOffset||PRESS_RETENTION_OFFSET;}, touchableGetHighlightDelayMS:function(){ return this.props.delayPressIn||0;}, touchableGetLongPressDelayMS:function(){ return this.props.delayLongPress===0?0: this.props.delayLongPress||500;}, touchableGetPressOutDelayMS:function(){ return this.props.delayPressOut;}, _opacityActive:function(){ this.setOpacityTo(this.props.activeOpacity);}, _opacityInactive:function(){ this.clearTimeout(this._hideTimeout); this._hideTimeout=null; var childStyle=flattenStyle(this.props.style)||{}; this.setOpacityTo( childStyle.opacity===undefined?1:childStyle.opacity);}, render:function(){ return ( React.createElement(Animated.View,{ accessible:true, accessibilityComponentType:this.props.accessibilityComponentType, accessibilityTraits:this.props.accessibilityTraits, style:[this.props.style,{opacity:this.state.anim}], testID:this.props.testID, onLayout:this.props.onLayout, onStartShouldSetResponder:this.touchableHandleStartShouldSetResponder, onResponderTerminationRequest:this.touchableHandleResponderTerminationRequest, onResponderGrant:this.touchableHandleResponderGrant, onResponderMove:this.touchableHandleResponderMove, onResponderRelease:this.touchableHandleResponderRelease, onResponderTerminate:this.touchableHandleResponderTerminate}, this.props.children));}}); module.exports=TouchableOpacity; }); __d('Animated',function(global, require, module, exports) { 'use strict'; var AnimatedImplementation=require('AnimatedImplementation'); var Image=require('Image'); var Text=require('Text'); var View=require('View'); module.exports=babelHelpers.extends({}, AnimatedImplementation,{ View:AnimatedImplementation.createAnimatedComponent(View), Text:AnimatedImplementation.createAnimatedComponent(Text), Image:AnimatedImplementation.createAnimatedComponent(Image)}); }); __d('AnimatedImplementation',function(global, require, module, exports) { 'use strict'; var Easing=require('Easing'); var InteractionManager=require('InteractionManager'); var Interpolation=require('Interpolation'); var React=require('React'); var Set=require('Set'); var SpringConfig=require('SpringConfig'); var ViewStylePropTypes=require('ViewStylePropTypes'); var flattenStyle=require('flattenStyle'); var invariant=require('invariant'); var requestAnimationFrame=require('requestAnimationFrame');var Animated=(function(){function Animated(){babelHelpers.classCallCheck(this,Animated);}babelHelpers.createClass(Animated,[{key:'__attach',value:function __attach() {}},{key:'__detach',value:function __detach() {}},{key:'__getValue',value:function __getValue() {}},{key:'__getAnimatedValue',value:function __getAnimatedValue() {return this.__getValue();}},{key:'__addChild',value:function __addChild( child){}},{key:'__removeChild',value:function __removeChild( child){}},{key:'__getChildren',value:function __getChildren() {return [];}}]);return Animated;})();var Animation=(function(){function Animation(){babelHelpers.classCallCheck(this,Animation);}babelHelpers.createClass(Animation,[{key:'start',value:function start( fromValue, onUpdate, onEnd, previousAnimation) {}},{key:'stop',value:function stop() {}},{key:'__debouncedOnEnd',value:function __debouncedOnEnd( result){ var onEnd=this.__onEnd; this.__onEnd=null; onEnd&&onEnd(result);}}]);return Animation;})();var AnimatedWithChildren=(function(_Animated){babelHelpers.inherits(AnimatedWithChildren,_Animated); function AnimatedWithChildren(){babelHelpers.classCallCheck(this,AnimatedWithChildren);var _this=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(AnimatedWithChildren).call(this)); _this._children=[];return _this;}babelHelpers.createClass(AnimatedWithChildren,[{key:'__addChild',value:function __addChild( child){ if(this._children.length===0){ this.__attach();} this._children.push(child);}},{key:'__removeChild',value:function __removeChild( child){ var index=this._children.indexOf(child); if(index===-1){ console.warn('Trying to remove a child that doesn\'t exist'); return;} this._children.splice(index,1); if(this._children.length===0){ this.__detach();}}},{key:'__getChildren',value:function __getChildren() { return this._children;}}]);return AnimatedWithChildren;})(Animated); function _flush(rootNode){ var animatedStyles=new Set(); function findAnimatedStyles(node){ if(typeof node.update==='function'){ animatedStyles.add(node);}else { node.__getChildren().forEach(findAnimatedStyles);}} findAnimatedStyles(rootNode); animatedStyles.forEach(function(animatedStyle){return animatedStyle.update();});} var easeInOut=Easing.inOut(Easing.ease);var TimingAnimation=(function(_Animation){babelHelpers.inherits(TimingAnimation,_Animation); function TimingAnimation( config) {babelHelpers.classCallCheck(this,TimingAnimation);var _this2=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(TimingAnimation).call(this)); _this2._toValue=config.toValue; _this2._easing=config.easing||easeInOut; _this2._duration=config.duration!==undefined?config.duration:500; _this2._delay=config.delay||0; _this2.__isInteraction=config.isInteraction!==undefined?config.isInteraction:true;return _this2;}babelHelpers.createClass(TimingAnimation,[{key:'start',value:function start( fromValue, onUpdate, onEnd) {var _this3=this; this.__active=true; this._fromValue=fromValue; this._onUpdate=onUpdate; this.__onEnd=onEnd; var start=function(){ if(_this3._duration===0){ _this3._onUpdate(_this3._toValue); _this3.__debouncedOnEnd({finished:true});}else { _this3._startTime=Date.now(); _this3._animationFrame=requestAnimationFrame(_this3.onUpdate.bind(_this3));}}; if(this._delay){ this._timeout=setTimeout(start,this._delay);}else { start();}}},{key:'onUpdate',value:function onUpdate() { var now=Date.now(); if(now>=this._startTime+this._duration){ if(this._duration===0){ this._onUpdate(this._toValue);}else { this._onUpdate( this._fromValue+this._easing(1)*(this._toValue-this._fromValue));} this.__debouncedOnEnd({finished:true}); return;} this._onUpdate( this._fromValue+ this._easing((now-this._startTime)/this._duration)*( this._toValue-this._fromValue)); if(this.__active){ this._animationFrame=requestAnimationFrame(this.onUpdate.bind(this));}}},{key:'stop',value:function stop() { this.__active=false; clearTimeout(this._timeout); window.cancelAnimationFrame(this._animationFrame); this.__debouncedOnEnd({finished:false});}}]);return TimingAnimation;})(Animation);var DecayAnimation=(function(_Animation2){babelHelpers.inherits(DecayAnimation,_Animation2); function DecayAnimation( config) {babelHelpers.classCallCheck(this,DecayAnimation);var _this4=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(DecayAnimation).call(this)); _this4._deceleration=config.deceleration||0.998; _this4._velocity=config.velocity; _this4.__isInteraction=config.isInteraction!==undefined?config.isInteraction:true;return _this4;}babelHelpers.createClass(DecayAnimation,[{key:'start',value:function start( fromValue, onUpdate, onEnd) { this.__active=true; this._lastValue=fromValue; this._fromValue=fromValue; this._onUpdate=onUpdate; this.__onEnd=onEnd; this._startTime=Date.now(); this._animationFrame=requestAnimationFrame(this.onUpdate.bind(this));}},{key:'onUpdate',value:function onUpdate() { var now=Date.now(); var value=this._fromValue+ this._velocity/(1-this._deceleration)*( 1-Math.exp(-(1-this._deceleration)*(now-this._startTime))); this._onUpdate(value); if(Math.abs(this._lastValue-value)<0.1){ this.__debouncedOnEnd({finished:true}); return;} this._lastValue=value; if(this.__active){ this._animationFrame=requestAnimationFrame(this.onUpdate.bind(this));}}},{key:'stop',value:function stop() { this.__active=false; window.cancelAnimationFrame(this._animationFrame); this.__debouncedOnEnd({finished:false});}}]);return DecayAnimation;})(Animation); function withDefault(value,defaultValue){ if(value===undefined||value===null){ return defaultValue;} return value;}var SpringAnimation=(function(_Animation3){babelHelpers.inherits(SpringAnimation,_Animation3); function SpringAnimation( config) {babelHelpers.classCallCheck(this,SpringAnimation);var _this5=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(SpringAnimation).call(this)); _this5._overshootClamping=withDefault(config.overshootClamping,false); _this5._restDisplacementThreshold=withDefault(config.restDisplacementThreshold,0.001); _this5._restSpeedThreshold=withDefault(config.restSpeedThreshold,0.001); _this5._initialVelocity=config.velocity; _this5._lastVelocity=withDefault(config.velocity,0); _this5._toValue=config.toValue; _this5.__isInteraction=config.isInteraction!==undefined?config.isInteraction:true; var springConfig; if(config.bounciness!==undefined||config.speed!==undefined){ invariant( config.tension===undefined&&config.friction===undefined, 'You can only define bounciness/speed or tension/friction but not both'); springConfig=SpringConfig.fromBouncinessAndSpeed( withDefault(config.bounciness,8), withDefault(config.speed,12));}else { springConfig=SpringConfig.fromOrigamiTensionAndFriction( withDefault(config.tension,40), withDefault(config.friction,7));} _this5._tension=springConfig.tension; _this5._friction=springConfig.friction;return _this5;}babelHelpers.createClass(SpringAnimation,[{key:'start',value:function start( fromValue, onUpdate, onEnd, previousAnimation) { this.__active=true; this._startPosition=fromValue; this._lastPosition=this._startPosition; this._onUpdate=onUpdate; this.__onEnd=onEnd; this._lastTime=Date.now(); if(previousAnimation instanceof SpringAnimation){ var internalState=previousAnimation.getInternalState(); this._lastPosition=internalState.lastPosition; this._lastVelocity=internalState.lastVelocity; this._lastTime=internalState.lastTime;} if(this._initialVelocity!==undefined&& this._initialVelocity!==null){ this._lastVelocity=this._initialVelocity;} this.onUpdate();}},{key:'getInternalState',value:function getInternalState() { return { lastPosition:this._lastPosition, lastVelocity:this._lastVelocity, lastTime:this._lastTime};}},{key:'onUpdate',value:function onUpdate() { var position=this._lastPosition; var velocity=this._lastVelocity; var tempPosition=this._lastPosition; var tempVelocity=this._lastVelocity; var MAX_STEPS=64; var now=Date.now(); if(now>this._lastTime+MAX_STEPS){ now=this._lastTime+MAX_STEPS;} var TIMESTEP_MSEC=1; var numSteps=Math.floor((now-this._lastTime)/TIMESTEP_MSEC); for(var i=0;ithis._toValue;}else { isOvershooting=positioninputMax){ if(extrapolateRight==='identity'){ return result;}else if(extrapolateRight==='clamp'){ result=inputMax;}else if(extrapolateRight==='extend'){}} if(outputMin===outputMax){ return outputMin;} if(inputMin===inputMax){ if(input<=inputMin){ return outputMin;} return outputMax;} if(inputMin===-Infinity){ result=-result;}else if(inputMax===Infinity){ result=result-inputMin;}else { result=(result-inputMin)/(inputMax-inputMin);} result=easing(result); if(outputMin===-Infinity){ result=-result;}else if(outputMax===Infinity){ result=result+outputMin;}else { result=result*(outputMax-outputMin)+outputMin;} return result;} function colorToRgba( input) { var color=tinycolor(input); if(color.isValid()){var _color$toRgb= color.toRgb();var r=_color$toRgb.r;var g=_color$toRgb.g;var b=_color$toRgb.b;var a=_color$toRgb.a; return 'rgba('+r+', '+g+', '+b+', '+(a===undefined?1:a)+')';}else { return input;}} var stringShapeRegex=/[0-9\.-]+/g; function createInterpolationFromStringOutputRange( config) { var outputRange=config.outputRange; invariant(outputRange.length>=2,'Bad output range'); outputRange=outputRange.map(colorToRgba); checkPattern(outputRange); var outputRanges=outputRange[0].match(stringShapeRegex).map(function(){return [];}); outputRange.forEach(function(value){ value.match(stringShapeRegex).forEach(function(number,i){ outputRanges[i].push(+number);});}); var interpolations=outputRange[0].match(stringShapeRegex).map(function(value,i){ return Interpolation.create(babelHelpers.extends({}, config,{ outputRange:outputRanges[i]}));}); return function(input){ var i=0; return outputRange[0].replace(stringShapeRegex,function(){ return String(interpolations[i++](input));});};} function checkPattern(arr){ var pattern=arr[0].replace(stringShapeRegex,''); for(var i=1;i=input){ break;}} return i-1;} function checkValidInputRange(arr){ invariant(arr.length>=2,'inputRange must have at least 2 elements'); for(var i=1;i=arr[i-1], 'inputRange must be monotonically increasing '+arr);}} function checkInfiniteRange(name,arr){ invariant(arr.length>=2,name+' must have at least 2 elements'); invariant( arr.length!==2||arr[0]!==-Infinity||arr[1]!==Infinity, name+'cannot be ]-infinity;+infinity[ '+arr);} module.exports=Interpolation; }); __d('Easing',function(global, require, module, exports) { 'use strict'; var _bezier=require('bezier');var Easing=(function(){function Easing(){babelHelpers.classCallCheck(this,Easing);}babelHelpers.createClass(Easing,null,[{key:'step0',value:function step0( n){ return n>0?1:0;}},{key:'step1',value:function step1( n){ return n>=1?1:0;}},{key:'linear',value:function linear( t){ return t;}},{key:'ease',value:function ease( t){ return _ease(t);}},{key:'quad',value:function quad( t){ return t*t;}},{key:'cubic',value:function cubic( t){ return t*t*t;}},{key:'poly',value:function poly( n){ return function(t){return Math.pow(t,n);};}},{key:'sin',value:function sin( t){ return 1-Math.cos(t*Math.PI/2);}},{key:'circle',value:function circle( t){ return 1-Math.sqrt(1-t*t);}},{key:'exp',value:function exp( t){ return Math.pow(2,10*(t-1));}},{key:'elastic',value:function elastic() {var bounciness=arguments.length<=0||arguments[0]===undefined?1:arguments[0]; var p=bounciness*Math.PI; return function(t){return 1-Math.pow(Math.cos(t*Math.PI/2),3)*Math.cos(t*p);};}},{key:'back',value:function back( s){ if(s===undefined){ s=1.70158;} return function(t){return t*t*((s+1)*t-s);};}},{key:'bounce',value:function bounce( t){ if(t<1/2.75){ return 7.5625*t*t;} if(t<2/2.75){ t-=1.5/2.75; return 7.5625*t*t+0.75;} if(t<2.5/2.75){ t-=2.25/2.75; return 7.5625*t*t+0.9375;} t-=2.625/2.75; return 7.5625*t*t+0.984375;}},{key:'bezier',value:function bezier( x1, y1, x2, y2, epsilon) { if(epsilon===undefined){ var duration=500; epsilon=1000/60/duration/4;} return _bezier(x1,y1,x2,y2,epsilon);}},{key:'in',value:function _in( easing) { return easing;}},{key:'out',value:function out( easing) { return function(t){return 1-easing(1-t);};}},{key:'inOut',value:function inOut( easing) { return function(t){ if(t<0.5){ return easing(t*2)/2;} return 1-easing((1-t)*2)/2;};}}]);return Easing;})(); var _ease=Easing.bezier(0.42,0,1,1); module.exports=Easing; }); __d('bezier',function(global, require, module, exports) { module. exports=function(x1,y1,x2,y2,epsilon){ var curveX=function(t){ var v=1-t; return 3*v*v*t*x1+3*v*t*t*x2+t*t*t;}; var curveY=function(t){ var v=1-t; return 3*v*v*t*y1+3*v*t*t*y2+t*t*t;}; var derivativeCurveX=function(t){ var v=1-t; return 3*(2*(t-1)*t+v*v)*x1+3*(-t*t*t+2*v*t)*x2;}; return function(t){ var x=t,t0,t1,t2,x2,d2,i; for(t2=x,i=0;i<8;i++){ x2=curveX(t2)-x; if(Math.abs(x2)t1)return curveY(t1); while(t0x2)t0=t2;else t1=t2; t2=(t1-t0)*.5+t0;} return curveY(t2);};}; }); __d('SpringConfig',function(global, require, module, exports) { 'use strict'; function tensionFromOrigamiValue(oValue){ return (oValue-30)*3.62+194;} function frictionFromOrigamiValue(oValue){ return (oValue-8)*3+25;} function fromOrigamiTensionAndFriction( tension, friction) { return { tension:tensionFromOrigamiValue(tension), friction:frictionFromOrigamiValue(friction)};} function fromBouncinessAndSpeed( bounciness, speed) { function normalize(value,startValue,endValue){ return (value-startValue)/(endValue-startValue);} function projectNormal(n,start,end){ return start+n*(end-start);} function linearInterpolation(t,start,end){ return t*end+(1-t)*start;} function quadraticOutInterpolation(t,start,end){ return linearInterpolation(2*t-t*t,start,end);} function b3Friction1(x){ return 0.0007*Math.pow(x,3)- 0.031*Math.pow(x,2)+0.64*x+1.28;} function b3Friction2(x){ return 0.000044*Math.pow(x,3)- 0.006*Math.pow(x,2)+0.36*x+2;} function b3Friction3(x){ return 0.00000045*Math.pow(x,3)- 0.000332*Math.pow(x,2)+0.1078*x+5.84;} function b3Nobounce(tension){ if(tension<=18){ return b3Friction1(tension);}else if(tension>18&&tension<=44){ return b3Friction2(tension);}else { return b3Friction3(tension);}} var b=normalize(bounciness/1.7,0,20); b=projectNormal(b,0,0.8); var s=normalize(speed/1.7,0,20); var bouncyTension=projectNormal(s,0.5,200); var bouncyFriction=quadraticOutInterpolation( b, b3Nobounce(bouncyTension), 0.01); return { tension:tensionFromOrigamiValue(bouncyTension), friction:frictionFromOrigamiValue(bouncyFriction)};} module.exports={ fromOrigamiTensionAndFriction:fromOrigamiTensionAndFriction, fromBouncinessAndSpeed:fromBouncinessAndSpeed}; }); __d('requestAnimationFrame',function(global, require, module, exports) { var emptyFunction=require('emptyFunction'); var nativeRequestAnimationFrame=require('nativeRequestAnimationFrame'); var lastTime=0; var requestAnimationFrame= nativeRequestAnimationFrame|| function(callback){ var currTime=Date.now(); var timeDelay=Math.max(0,16-(currTime-lastTime)); lastTime=currTime+timeDelay; return global.setTimeout(function(){ callback(Date.now());}, timeDelay);}; requestAnimationFrame(emptyFunction); module.exports=requestAnimationFrame; }); __d('nativeRequestAnimationFrame',function(global, require, module, exports) { var nativeRequestAnimationFrame= global.requestAnimationFrame|| global.webkitRequestAnimationFrame|| global.mozRequestAnimationFrame|| global.oRequestAnimationFrame|| global.msRequestAnimationFrame; module.exports=nativeRequestAnimationFrame; }); __d('ViewPagerAndroid',function(global, require, module, exports) { 'use strict'; module.exports=require('UnimplementedView'); }); __d('WebView',function(global, require, module, exports) { 'use strict'; var ActivityIndicatorIOS=require('ActivityIndicatorIOS'); var EdgeInsetsPropType=require('EdgeInsetsPropType'); var React=require('React'); var StyleSheet=require('StyleSheet'); var Text=require('Text'); var View=require('View'); var invariant=require('invariant'); var keyMirror=require('keyMirror'); var requireNativeComponent=require('requireNativeComponent'); var PropTypes=React.PropTypes; var RCTWebViewManager=require('NativeModules').WebViewManager; var BGWASH='rgba(255,255,255,0.8)'; var RCT_WEBVIEW_REF='webview'; var WebViewState=keyMirror({ IDLE:null, LOADING:null, ERROR:null}); var NavigationType={ click:RCTWebViewManager.NavigationType.LinkClicked, formsubmit:RCTWebViewManager.NavigationType.FormSubmitted, backforward:RCTWebViewManager.NavigationType.BackForward, reload:RCTWebViewManager.NavigationType.Reload, formresubmit:RCTWebViewManager.NavigationType.FormResubmitted, other:RCTWebViewManager.NavigationType.Other}; var JSNavigationScheme=RCTWebViewManager.JSNavigationScheme; var defaultRenderLoading=function(){return ( React.createElement(View,{style:styles.loadingView}, React.createElement(ActivityIndicatorIOS,null)));}; var defaultRenderError=function(errorDomain,errorCode,errorDesc){return ( React.createElement(View,{style:styles.errorContainer}, React.createElement(Text,{style:styles.errorTextTitle},'Error loading page'), React.createElement(Text,{style:styles.errorText}, 'Domain: '+errorDomain), React.createElement(Text,{style:styles.errorText}, 'Error Code: '+errorCode), React.createElement(Text,{style:styles.errorText}, 'Description: '+errorDesc)));}; var WebView=React.createClass({displayName:'WebView', statics:{ JSNavigationScheme:JSNavigationScheme, NavigationType:NavigationType}, propTypes:babelHelpers.extends({}, View.propTypes,{ url:PropTypes.string, html:PropTypes.string, renderError:PropTypes.func, renderLoading:PropTypes.func, bounces:PropTypes.bool, scrollEnabled:PropTypes.bool, automaticallyAdjustContentInsets:PropTypes.bool, contentInset:EdgeInsetsPropType, onNavigationStateChange:PropTypes.func, startInLoadingState:PropTypes.bool, style:View.propTypes.style, javaScriptEnabledAndroid:PropTypes.bool, injectedJavaScript:PropTypes.string, scalesPageToFit:PropTypes.bool, onShouldStartLoadWithRequest:PropTypes.func, allowsInlineMediaPlayback:PropTypes.bool}), getInitialState:function(){ return { viewState:WebViewState.IDLE, lastErrorEvent:null, startInLoadingState:true};}, componentWillMount:function(){ if(this.props.startInLoadingState){ this.setState({viewState:WebViewState.LOADING});}}, render:function(){var _this=this; var otherView=null; if(this.state.viewState===WebViewState.LOADING){ otherView=(this.props.renderLoading||defaultRenderLoading)();}else if(this.state.viewState===WebViewState.ERROR){ var errorEvent=this.state.lastErrorEvent; invariant( errorEvent!=null, 'lastErrorEvent expected to be non-null'); otherView=(this.props.renderError||defaultRenderError)( errorEvent.domain, errorEvent.code, errorEvent.description);}else if(this.state.viewState!==WebViewState.IDLE){ console.error( 'RCTWebView invalid state encountered: '+this.state.loading);} var webViewStyles=[styles.container,styles.webView,this.props.style]; if(this.state.viewState===WebViewState.LOADING|| this.state.viewState===WebViewState.ERROR){ webViewStyles.push(styles.hidden);} var onShouldStartLoadWithRequest=this.props.onShouldStartLoadWithRequest&&function(event){ var shouldStart=_this.props.onShouldStartLoadWithRequest&& _this.props.onShouldStartLoadWithRequest(event.nativeEvent); RCTWebViewManager.startLoadWithResult(!!shouldStart,event.nativeEvent.lockIdentifier);}; var webView= React.createElement(RCTWebView,{ ref:RCT_WEBVIEW_REF, key:'webViewKey', style:webViewStyles, url:this.props.url, html:this.props.html, injectedJavaScript:this.props.injectedJavaScript, bounces:this.props.bounces, scrollEnabled:this.props.scrollEnabled, contentInset:this.props.contentInset, automaticallyAdjustContentInsets:this.props.automaticallyAdjustContentInsets, onLoadingStart:this.onLoadingStart, onLoadingFinish:this.onLoadingFinish, onLoadingError:this.onLoadingError, onShouldStartLoadWithRequest:onShouldStartLoadWithRequest, scalesPageToFit:this.props.scalesPageToFit, allowsInlineMediaPlayback:this.props.allowsInlineMediaPlayback}); return ( React.createElement(View,{style:styles.container}, webView, otherView));}, goForward:function(){ RCTWebViewManager.goForward(this.getWebViewHandle());}, goBack:function(){ RCTWebViewManager.goBack(this.getWebViewHandle());}, reload:function(){ RCTWebViewManager.reload(this.getWebViewHandle());}, updateNavigationState:function(event){ if(this.props.onNavigationStateChange){ this.props.onNavigationStateChange(event.nativeEvent);}}, getWebViewHandle:function(){ return React.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);}, onLoadingStart:function(event){ this.updateNavigationState(event);}, onLoadingError:function(event){ event.persist(); console.warn('Encountered an error loading page',event.nativeEvent); this.setState({ lastErrorEvent:event.nativeEvent, viewState:WebViewState.ERROR});}, onLoadingFinish:function(event){ this.setState({ viewState:WebViewState.IDLE}); this.updateNavigationState(event);}}); var RCTWebView=requireNativeComponent('RCTWebView',WebView,{ nativeOnly:{ onLoadingStart:true, onLoadingError:true, onLoadingFinish:true}}); var styles=StyleSheet.create({ container:{ flex:1}, errorContainer:{ flex:1, justifyContent:'center', alignItems:'center', backgroundColor:BGWASH}, errorText:{ fontSize:14, textAlign:'center', marginBottom:2}, errorTextTitle:{ fontSize:15, fontWeight:'500', marginBottom:10}, hidden:{ height:0, flex:0}, loadingView:{ backgroundColor:BGWASH, flex:1, justifyContent:'center', alignItems:'center'}, webView:{ backgroundColor:'#ffffff'}}); module.exports=WebView; }); __d('ActionSheetIOS',function(global, require, module, exports) { 'use strict'; var RCTActionSheetManager=require('NativeModules').ActionSheetManager; var invariant=require('invariant'); var ActionSheetIOS={ showActionSheetWithOptions:function(options,callback){ invariant( typeof options==='object'&&options!==null, 'Options must a valid object'); invariant( typeof callback==='function', 'Must provide a valid callback'); RCTActionSheetManager.showActionSheetWithOptions( options, callback);}, showShareActionSheetWithOptions:function( options, failureCallback, successCallback) { invariant( typeof options==='object'&&options!==null, 'Options must a valid object'); invariant( typeof failureCallback==='function', 'Must provide a valid failureCallback'); invariant( typeof successCallback==='function', 'Must provide a valid successCallback'); RCTActionSheetManager.showShareActionSheetWithOptions( options, failureCallback, successCallback);}}; module.exports=ActionSheetIOS; }); __d('AdSupportIOS',function(global, require, module, exports) { 'use strict'; var AdSupport=require('NativeModules').AdSupport; module.exports={ getAdvertisingId:function(onSuccess,onFailure){ AdSupport.getAdvertisingId(onSuccess,onFailure);}, getAdvertisingTrackingEnabled:function(onSuccess,onFailure){ AdSupport.getAdvertisingTrackingEnabled(onSuccess,onFailure);}}; }); __d('AlertIOS',function(global, require, module, exports) { 'use strict'; var RCTAlertManager=require('NativeModules').AlertManager; var invariant=require('invariant'); var DEFAULT_BUTTON_TEXT='OK'; var DEFAULT_BUTTON={ text:DEFAULT_BUTTON_TEXT, onPress:null};var AlertIOS=(function(){function AlertIOS(){babelHelpers.classCallCheck(this,AlertIOS);}babelHelpers.createClass(AlertIOS,null,[{key:'alert',value:function alert( title, message, buttons, type) { var callbacks=[]; var buttonsSpec=[]; title=title||''; message=message||''; buttons=buttons||[DEFAULT_BUTTON]; type=type||''; buttons.forEach(function(btn,index){ callbacks[index]=btn.onPress; var btnDef={}; btnDef[index]=btn.text||DEFAULT_BUTTON_TEXT; buttonsSpec.push(btnDef);}); RCTAlertManager.alertWithArgs({ title:title, message:message, buttons:buttonsSpec, type:type}, function(id,value){ var cb=callbacks[id]; cb&&cb(value);});}},{key:'prompt',value:function prompt( title, value, buttons, callback) { if(arguments.length===2){ if(typeof value==='object'){ buttons=value; value=undefined;}else if(typeof value==='function'){ callback=value; value=undefined;}}else if(arguments.length===3&&typeof buttons==='function'){ callback=buttons; buttons=undefined;} invariant( !(callback&&buttons)&&(callback||buttons), 'Must provide either a button list or a callback, but not both'); if(!buttons){ buttons=[{ text:'Cancel'}, { text:'OK', onPress:callback}];} this.alert(title,value,buttons,'plain-text');}}]);return AlertIOS;})(); module.exports=AlertIOS; }); __d('AppRegistry',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); var renderApplication=require('renderApplication'); if(__DEV__){ require('RCTRenderingPerf');} var runnables={}; var AppRegistry={ registerConfig:function(config){ for(var i=0;iDimensions.get('window').height/2?'top':'bottom', selection:hierarchy.length-1, hierarchy:hierarchy, inspected:{ style:props.style||{}, frame:frame}});}},{key:'setPerfing',value:function setPerfing( val){ this.setState({ perfing:val, inspecting:false, inspected:null});}},{key:'setInspecting',value:function setInspecting( val){ this.setState({ inspecting:val, inspected:null});}},{key:'render',value:function render() { var panelContainerStyle=this.state.panelPos==='bottom'?{bottom:0}:{top:0}; return ( React.createElement(View,{style:styles.container,pointerEvents:'box-none'}, this.state.inspecting&& React.createElement(InspectorOverlay,{ rootTag:this.props.rootTag, inspected:this.state.inspected, inspectedViewTag:this.props.inspectedViewTag, onTouchInstance:this.onTouchInstance.bind(this)}), React.createElement(View,{style:[styles.panelContainer,panelContainerStyle]}, React.createElement(InspectorPanel,{ devtoolsIsOpen:!!this.state.devtoolsAgent, inspecting:this.state.inspecting, perfing:this.state.perfing, setPerfing:this.setPerfing.bind(this), setInspecting:this.setInspecting.bind(this), inspected:this.state.inspected, hierarchy:this.state.hierarchy, selection:this.state.selection, setSelection:this.setSelection.bind(this)}))));}}]);return Inspector;})(React.Component); var styles=StyleSheet.create({ container:{ position:'absolute', backgroundColor:'transparent', top:0, left:0, right:0, bottom:0}, panelContainer:{ position:'absolute', left:0, right:0}}); module.exports=Inspector; }); __d('InspectorOverlay',function(global, require, module, exports) { 'use strict'; var Dimensions=require('Dimensions'); var InspectorUtils=require('InspectorUtils'); var React=require('React'); var StyleSheet=require('StyleSheet'); var UIManager=require('NativeModules').UIManager; var View=require('View'); var ElementBox=require('ElementBox'); var PropTypes=React.PropTypes; var InspectorOverlay=React.createClass({displayName:'InspectorOverlay', propTypes:{ inspected:PropTypes.shape({ frame:PropTypes.object, style:PropTypes.any}), inspectedViewTag:PropTypes.number, onTouchInstance:PropTypes.func.isRequired}, findViewForTouchEvent:function(e){var _this=this;var _e$nativeEvent$touche= e.nativeEvent.touches[0];var locationX=_e$nativeEvent$touche.locationX;var locationY=_e$nativeEvent$touche.locationY; UIManager.findSubviewIn( this.props.inspectedViewTag, [locationX,locationY], function(nativeViewTag,left,top,width,height){ var instance=InspectorUtils.findInstanceByNativeTag(_this.props.rootTag,nativeViewTag); if(!instance){ return;} _this.props.onTouchInstance(instance,{left:left,top:top,width:width,height:height},locationY);});}, shouldSetResponser:function(e){ this.findViewForTouchEvent(e); return true;}, render:function(){ var content=null; if(this.props.inspected){ content=React.createElement(ElementBox,{frame:this.props.inspected.frame,style:this.props.inspected.style});} return ( React.createElement(View,{ onStartShouldSetResponder:this.shouldSetResponser, onResponderMove:this.findViewForTouchEvent, style:[styles.inspector,{height:Dimensions.get('window').height}]}, content));}}); var styles=StyleSheet.create({ inspector:{ backgroundColor:'transparent', position:'absolute', left:0, top:0, right:0}}); module.exports=InspectorOverlay; }); __d('ElementBox',function(global, require, module, exports) { 'use strict'; var React=require('React'); var View=require('View'); var StyleSheet=require('StyleSheet'); var BorderBox=require('BorderBox'); var resolveBoxStyle=require('resolveBoxStyle'); var flattenStyle=require('flattenStyle');var ElementBox=(function(_React$Component){babelHelpers.inherits(ElementBox,_React$Component);function ElementBox(){babelHelpers.classCallCheck(this,ElementBox);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(ElementBox).apply(this,arguments));}babelHelpers.createClass(ElementBox,[{key:'render',value:function render() { var style=flattenStyle(this.props.style)||{}; var margin=resolveBoxStyle('margin',style); var padding=resolveBoxStyle('padding',style); var frameStyle=this.props.frame; if(margin){ frameStyle={ top:frameStyle.top-margin.top, left:frameStyle.left-margin.left, height:frameStyle.height+margin.top+margin.bottom, width:frameStyle.width+margin.left+margin.right};} var contentStyle={ width:this.props.frame.width, height:this.props.frame.height}; if(padding){ contentStyle={ width:contentStyle.width-padding.left-padding.right, height:contentStyle.height-padding.top-padding.bottom};} return ( React.createElement(View,{style:[styles.frame,frameStyle],pointerEvents:'none'}, React.createElement(BorderBox,{box:margin,style:styles.margin}, React.createElement(BorderBox,{box:padding,style:styles.padding}, React.createElement(View,{style:[styles.content,contentStyle]})))));}}]);return ElementBox;})(React.Component); var styles=StyleSheet.create({ frame:{ position:'absolute'}, content:{ backgroundColor:'rgba(200, 230, 255, 0.8)'}, padding:{ borderColor:'rgba(77, 255, 0, 0.3)'}, margin:{ borderColor:'rgba(255, 132, 0, 0.3)'}}); module.exports=ElementBox; }); __d('BorderBox',function(global, require, module, exports) { 'use strict'; var React=require('React'); var View=require('View');var BorderBox=(function(_React$Component){babelHelpers.inherits(BorderBox,_React$Component);function BorderBox(){babelHelpers.classCallCheck(this,BorderBox);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(BorderBox).apply(this,arguments));}babelHelpers.createClass(BorderBox,[{key:'render',value:function render() { var box=this.props.box; if(!box){ return this.props.children;} var style={ borderTopWidth:box.top, borderBottomWidth:box.bottom, borderLeftWidth:box.left, borderRightWidth:box.right}; return ( React.createElement(View,{style:[style,this.props.style]}, this.props.children));}}]);return BorderBox;})(React.Component); module.exports=BorderBox; }); __d('resolveBoxStyle',function(global, require, module, exports) { 'use strict'; function resolveBoxStyle(prefix,style){ var res={}; var subs=['top','left','bottom','right']; var set=false; subs.forEach(function(sub){ res[sub]=style[prefix]||0;}); if(style[prefix]){ set=true;} if(style[prefix+'Vertical']){ res.top=res.bottom=style[prefix+'Vertical']; set=true;} if(style[prefix+'Horizontal']){ res.left=res.right=style[prefix+'Horizontal']; set=true;} subs.forEach(function(sub){ var val=style[prefix+capFirst(sub)]; if(val){ res[sub]=val; set=true;}}); if(!set){ return;} return res;} function capFirst(text){ return text[0].toUpperCase()+text.slice(1);} module.exports=resolveBoxStyle; }); __d('InspectorPanel',function(global, require, module, exports) { 'use strict'; var React=require('React'); var StyleSheet=require('StyleSheet'); var Text=require('Text'); var View=require('View'); var ElementProperties=require('ElementProperties'); var PerformanceOverlay=require('PerformanceOverlay'); var TouchableHighlight=require('TouchableHighlight'); var PropTypes=React.PropTypes;var InspectorPanel=(function(_React$Component){babelHelpers.inherits(InspectorPanel,_React$Component);function InspectorPanel(){babelHelpers.classCallCheck(this,InspectorPanel);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(InspectorPanel).apply(this,arguments));}babelHelpers.createClass(InspectorPanel,[{key:'renderWaiting',value:function renderWaiting() { if(this.props.inspecting){ return ( React.createElement(Text,{style:styles.waitingText},'Tap something to inspect it'));} return React.createElement(Text,{style:styles.waitingText},'Nothing is inspected');}},{key:'render',value:function render() { var contents; if(this.props.inspected){ contents= React.createElement(ElementProperties,{ style:this.props.inspected.style, frame:this.props.inspected.frame, hierarchy:this.props.hierarchy, selection:this.props.selection, setSelection:this.props.setSelection});}else if(this.props.perfing){ contents= React.createElement(PerformanceOverlay,null);}else { contents= React.createElement(View,{style:styles.waiting}, this.renderWaiting());} return ( React.createElement(View,{style:styles.container}, !this.props.devtoolsIsOpen&&contents, React.createElement(View,{style:styles.buttonRow}, React.createElement(Button,{ title:'Inspect', pressed:this.props.inspecting, onClick:this.props.setInspecting}), React.createElement(Button,{title:'Perf', pressed:this.props.perfing, onClick:this.props.setPerfing}))));}}]);return InspectorPanel;})(React.Component); InspectorPanel.propTypes={ devtoolsIsOpen:PropTypes.bool, inspecting:PropTypes.bool, setInspecting:PropTypes.func, inspected:PropTypes.object, perfing:PropTypes.bool, setPerfing:PropTypes.func};var Button=(function(_React$Component2){babelHelpers.inherits(Button,_React$Component2);function Button(){babelHelpers.classCallCheck(this,Button);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(Button).apply(this,arguments));}babelHelpers.createClass(Button,[{key:'render',value:function render() {var _this3=this; return ( React.createElement(TouchableHighlight,{onPress:function(){return _this3.props.onClick(!_this3.props.pressed);},style:[ styles.button, this.props.pressed&&styles.buttonPressed]}, React.createElement(Text,{style:styles.buttonText},this.props.title)));}}]);return Button;})(React.Component); var styles=StyleSheet.create({ buttonRow:{ flexDirection:'row'}, button:{ backgroundColor:'rgba(0, 0, 0, 0.3)', margin:2, height:30, justifyContent:'center', alignItems:'center'}, buttonPressed:{ backgroundColor:'rgba(255, 255, 255, 0.3)'}, buttonText:{ textAlign:'center', color:'white', margin:5}, container:{ backgroundColor:'rgba(0, 0, 0, 0.7)'}, waiting:{ height:100}, waitingText:{ fontSize:20, textAlign:'center', marginVertical:20}}); module.exports=InspectorPanel; }); __d('ElementProperties',function(global, require, module, exports) { 'use strict'; var BoxInspector=require('BoxInspector'); var PropTypes=require('ReactPropTypes'); var React=require('React'); var StyleInspector=require('StyleInspector'); var StyleSheet=require('StyleSheet'); var Text=require('Text'); var TouchableHighlight=require('TouchableHighlight'); var TouchableWithoutFeedback=require('TouchableWithoutFeedback'); var View=require('View'); var flattenStyle=require('flattenStyle'); var mapWithSeparator=require('mapWithSeparator'); var ElementProperties=React.createClass({displayName:'ElementProperties', propTypes:{ hierarchy:PropTypes.array.isRequired, style:PropTypes.oneOfType([ PropTypes.object, PropTypes.array, PropTypes.number])}, render:function(){var _this=this; var style=flattenStyle(this.props.style); var selection=this.props.selection; return ( React.createElement(TouchableWithoutFeedback,null, React.createElement(View,{style:styles.info}, React.createElement(View,{style:styles.breadcrumb}, mapWithSeparator( this.props.hierarchy, function(item,i){return ( React.createElement(TouchableHighlight,{ style:[styles.breadItem,i===selection&&styles.selected], onPress:function(){return _this.props.setSelection(i);}}, React.createElement(Text,{style:styles.breadItemText}, item.getName?item.getName():'Unknown')));}, function(){return React.createElement(Text,{style:styles.breadSep},'▸');})), React.createElement(View,{style:styles.row}, React.createElement(StyleInspector,{style:style}), React.createElement(BoxInspector,{style:style,frame:this.props.frame})))));}}); var styles=StyleSheet.create({ breadSep:{ fontSize:8, color:'white'}, breadcrumb:{ flexDirection:'row', flexWrap:'wrap', marginBottom:5}, selected:{ borderColor:'white', borderRadius:5}, breadItem:{ borderWidth:1, borderColor:'transparent', marginHorizontal:2}, breadItemText:{ fontSize:10, color:'white', marginHorizontal:5}, row:{ flexDirection:'row', alignItems:'center', justifyContent:'space-between'}, info:{ padding:10}, path:{ color:'white', fontSize:9}}); module.exports=ElementProperties; }); __d('BoxInspector',function(global, require, module, exports) { 'use strict'; var React=require('React'); var StyleSheet=require('StyleSheet'); var Text=require('Text'); var View=require('View'); var resolveBoxStyle=require('resolveBoxStyle'); var blank={ top:0, left:0, right:0, bottom:0};var BoxInspector=(function(_React$Component){babelHelpers.inherits(BoxInspector,_React$Component);function BoxInspector(){babelHelpers.classCallCheck(this,BoxInspector);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(BoxInspector).apply(this,arguments));}babelHelpers.createClass(BoxInspector,[{key:'render',value:function render() { var frame=this.props.frame; var style=this.props.style; var margin=style&&resolveBoxStyle('margin',style)||blank; var padding=style&&resolveBoxStyle('padding',style)||blank; return ( React.createElement(BoxContainer,{title:'margin',titleStyle:styles.marginLabel,box:margin}, React.createElement(BoxContainer,{title:'padding',box:padding}, React.createElement(View,null, React.createElement(Text,{style:styles.innerText},'(', frame.left,', ',frame.top,')'), React.createElement(Text,{style:styles.innerText}, frame.width,' × ',frame.height)))));}}]);return BoxInspector;})(React.Component);var BoxContainer=(function(_React$Component2){babelHelpers.inherits(BoxContainer,_React$Component2);function BoxContainer(){babelHelpers.classCallCheck(this,BoxContainer);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(BoxContainer).apply(this,arguments));}babelHelpers.createClass(BoxContainer,[{key:'render',value:function render() { var box=this.props.box; return ( React.createElement(View,{style:styles.box}, React.createElement(View,{style:styles.row}, React.createElement(Text,{style:[this.props.titleStyle,styles.label]},this.props.title), React.createElement(Text,{style:styles.boxText},box.top)), React.createElement(View,{style:styles.row}, React.createElement(Text,{style:styles.boxText},box.left), this.props.children, React.createElement(Text,{style:styles.boxText},box.right)), React.createElement(Text,{style:styles.boxText},box.bottom)));}}]);return BoxContainer;})(React.Component); var styles=StyleSheet.create({ row:{ flexDirection:'row', alignItems:'center', justifyContent:'space-around'}, marginLabel:{ width:60}, label:{ fontSize:10, color:'rgb(255,100,0)', marginLeft:5, flex:1, textAlign:'left', top:-3}, buffer:{ fontSize:10, color:'yellow', flex:1, textAlign:'center'}, innerText:{ color:'yellow', fontSize:12, textAlign:'center', width:70}, box:{ borderWidth:1, borderColor:'grey'}, boxText:{ color:'white', fontSize:12, marginHorizontal:3, marginVertical:2, textAlign:'center'}}); module.exports=BoxInspector; }); __d('StyleInspector',function(global, require, module, exports) { 'use strict'; var React=require('React'); var StyleSheet=require('StyleSheet'); var Text=require('Text'); var View=require('View');var StyleInspector=(function(_React$Component){babelHelpers.inherits(StyleInspector,_React$Component);function StyleInspector(){babelHelpers.classCallCheck(this,StyleInspector);return babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(StyleInspector).apply(this,arguments));}babelHelpers.createClass(StyleInspector,[{key:'render',value:function render() {var _this2=this; if(!this.props.style){ return React.createElement(Text,{style:styles.noStyle},'No style');} var names=Object.keys(this.props.style); return ( React.createElement(View,{style:styles.container}, React.createElement(View,null, names.map(function(name){return React.createElement(Text,{style:styles.attr},name,':');})), React.createElement(View,null, names.map(function(name){return React.createElement(Text,{style:styles.value},_this2.props.style[name]);}))));}}]);return StyleInspector;})(React.Component); var styles=StyleSheet.create({ container:{ flexDirection:'row'}, row:{ flexDirection:'row', alignItems:'center', justifyContent:'space-around'}, attr:{ fontSize:10, color:'#ccc'}, value:{ fontSize:10, color:'white', marginLeft:10}, noStyle:{ color:'white', fontSize:10}}); module.exports=StyleInspector; }); __d('mapWithSeparator',function(global, require, module, exports) { 'use strict'; function mapWithSeparator(array,valueFunction,separatorFunction){ var results=[]; for(var i=0;i1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];} var index=0; return format.replace(/%s/g,function(match){return args[index++];});} function updateWarningMap(format){ var stringifySafe=require('stringifySafe'); format=String(format); var argCount=(format.match(/%s/g)||[]).length;for(var _len2=arguments.length,args=Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];} var warning=[ sprintf.apply(undefined,[format].concat(babelHelpers.toConsumableArray(args.slice(0,argCount))))].concat(babelHelpers.toConsumableArray( args.slice(argCount).map(stringifySafe))). join(' '); var count=_warningMap.has(warning)?_warningMap.get(warning):0; _warningMap.set(warning,count+2); _warningEmitter.emit('warning',_warningMap);} function isWarningIgnored(warning){ return ( Array.isArray(console.ignoredYellowBox)&& console.ignoredYellowBox.some( function(ignorePrefix){return warning.startsWith(ignorePrefix);}));} var WarningRow=function(_ref){var count=_ref.count;var warning=_ref.warning;var onPress=_ref.onPress; var Text=require('Text'); var TouchableHighlight=require('TouchableHighlight'); var View=require('View'); var countText=count>1? React.createElement(Text,{style:styles.listRowCount},'('+count+') '): null; return ( React.createElement(View,{style:styles.listRow}, React.createElement(TouchableHighlight,{ activeOpacity:0.5, onPress:onPress, style:styles.listRowContent, underlayColor:'transparent'}, React.createElement(Text,{style:styles.listRowText,numberOfLines:2}, countText, warning))));}; var WarningInspector=function(_ref2){var count=_ref2.count;var warning=_ref2.warning;var onClose=_ref2.onClose;var onDismiss=_ref2.onDismiss; var ScrollView=require('ScrollView'); var Text=require('Text'); var TouchableHighlight=require('TouchableHighlight'); var View=require('View'); var countSentence= 'Warning encountered '+count+' time'+(count-1?'s':'')+'.'; return ( React.createElement(TouchableHighlight,{ activeOpacity:0.95, underlayColor:backgroundColor(0.8), onPress:onClose, style:styles.inspector}, React.createElement(View,{style:styles.inspectorContent}, React.createElement(View,{style:styles.inspectorCount}, React.createElement(Text,{style:styles.inspectorCountText},countSentence)), React.createElement(ScrollView,{style:styles.inspectorWarning}, React.createElement(Text,{style:styles.inspectorWarningText},warning)), React.createElement(View,{style:styles.inspectorButtons}, React.createElement(TouchableHighlight,{ activeOpacity:0.5, onPress:onDismiss, style:styles.inspectorButton, underlayColor:'transparent'}, React.createElement(Text,{style:styles.inspectorButtonText},'Dismiss Warning'))))));};var YellowBox=(function(_React$Component){babelHelpers.inherits(YellowBox,_React$Component); function YellowBox(props,context){babelHelpers.classCallCheck(this,YellowBox);var _this=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(YellowBox).call(this, props,context)); _this.state={ inspecting:null, warningMap:_warningMap}; _this.dismissWarning=function(warning){var _this$state= _this.state;var inspecting=_this$state.inspecting;var warningMap=_this$state.warningMap; warningMap.delete(warning); _this.setState({ inspecting:inspecting===warning?null:inspecting, warningMap:warningMap});};return _this;}babelHelpers.createClass(YellowBox,[{key:'componentDidMount',value:function componentDidMount() {var _this2=this; var scheduled=null; this._listener=_warningEmitter.addListener('warning',function(warningMap){ scheduled=scheduled||setImmediate(function(){ scheduled=null; _this2.setState({ warningMap:warningMap});});});}},{key:'componentWillUnmount',value:function componentWillUnmount() { if(this._listener){ this._listener.remove();}}},{key:'render',value:function render() {var _this3=this; if(console.disableYellowBox||this.state.warningMap.size===0){ return null;} var ScrollView=require('ScrollView'); var View=require('View'); var inspecting=this.state.inspecting; var inspector=inspecting!==null? React.createElement(WarningInspector,{ count:this.state.warningMap.get(inspecting), warning:inspecting, onClose:function(){return _this3.setState({inspecting:null});}, onDismiss:function(){return _this3.dismissWarning(inspecting);}}): null; var rows=[]; this.state.warningMap.forEach(function(count,warning){ if(!isWarningIgnored(warning)){ rows.push( React.createElement(WarningRow,{ key:warning, count:count, warning:warning, onPress:function(){return _this3.setState({inspecting:warning});}, onDismiss:function(){return _this3.dismissWarning(warning);}}));}}); var listStyle=[ styles.list, {height:Math.min(rows.length,4.4)*(rowGutter+rowHeight)}]; return ( React.createElement(View,{style:inspector?styles.fullScreen:listStyle}, React.createElement(ScrollView,{style:listStyle}, rows), inspector));}}]);return YellowBox;})(React.Component); var backgroundColor=function(opacity){return 'rgba(250, 186, 48, '+opacity+')';}; var textColor='white'; var rowGutter=1; var rowHeight=46; var styles=StyleSheet.create({ fullScreen:{ backgroundColor:'transparent', position:'absolute', left:0, right:0, top:0, bottom:0}, inspector:{ backgroundColor:backgroundColor(0.95), flex:1}, inspectorContainer:{ flex:1}, inspectorButtons:{ flexDirection:'row', position:'absolute', left:0, right:0, bottom:0}, inspectorButton:{ padding:22, position:'absolute', left:0, right:0, bottom:0}, inspectorButtonText:{ color:textColor, fontSize:14, opacity:0.8, textAlign:'center'}, inspectorContent:{ flex:1, paddingTop:5}, inspectorCount:{ padding:15, paddingBottom:0}, inspectorCountText:{ color:textColor, fontSize:14}, inspectorWarning:{ padding:15, position:'absolute', top:39, bottom:60}, inspectorWarningText:{ color:textColor, fontSize:16, fontWeight:'600'}, list:{ backgroundColor:'transparent', position:'absolute', left:0, right:0, bottom:0}, listRow:{ position:'relative', backgroundColor:backgroundColor(0.95), flex:1, height:rowHeight, marginTop:rowGutter}, listRowContent:{ flex:1}, listRowCount:{ color:'rgba(255, 255, 255, 0.5)'}, listRowText:{ color:textColor, position:'absolute', left:0, top:Platform.OS==='android'?5:7, marginLeft:15, marginRight:15}}); module.exports=YellowBox; }); __d('RCTRenderingPerf',function(global, require, module, exports) { 'use strict'; var ReactDefaultPerf=require('ReactDefaultPerf'); var invariant=require('invariant'); var perfModules=[]; var enabled=false; var RCTRenderingPerf={ toggle:function(){ console.log('Render perfomance measurements enabled'); enabled=true;}, start:function(){ if(!enabled){ return;} ReactDefaultPerf.start(); perfModules.forEach(function(module){return module.start();});}, stop:function(){ if(!enabled){ return;} ReactDefaultPerf.stop(); ReactDefaultPerf.printInclusive(); ReactDefaultPerf.printWasted(); var totalRender=0; var totalTime=0; var measurements=ReactDefaultPerf.getLastMeasurements(); for(var ii=0;ii 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){ 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'){ 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'){ 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 { 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'|| 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(): ''}; return rv;}else { return func.apply(this,args);}};}}; module.exports=ReactDefaultPerf; }); __d('DOMProperty',function(global, require, module, exports) { 'use strict'; var invariant=require('invariant'); function checkMask(value,bitmask){ return (value&bitmask)===bitmask;} var DOMPropertyInjection={ 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, 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){ invariant( !DOMProperty.properties.hasOwnProperty(propName), 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property '+ '\'%s\' which has already been injected. You may be accidentally '+ 'injecting the same DOM property config twice, or you may be '+ 'injecting two configs that have conflicting property names.', propName); 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)}; invariant( !propertyInfo.mustUseAttribute||!propertyInfo.mustUseProperty, 'DOMProperty: Cannot require using both attribute and property: %s', propName); invariant( propertyInfo.mustUseProperty||!propertyInfo.hasSideEffects, 'DOMProperty: Properties that have side effects must use property: %s', propName); invariant( propertyInfo.hasBooleanValue+propertyInfo.hasNumericValue+ propertyInfo.hasOverloadedBooleanValue<=1, 'DOMProperty: Value can be one of boolean, overloaded boolean, or '+ 'numeric value, but not a combination: %s', propName); if(__DEV__){ DOMProperty.getPossibleStandardName[lowerCased]=propName;} if(DOMAttributeNames.hasOwnProperty(propName)){ var attributeName=DOMAttributeNames[propName]; propertyInfo.attributeName=attributeName; if(__DEV__){ 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={}; var DOMProperty={ ID_ATTRIBUTE_NAME:'data-reactid', properties:{}, getPossibleStandardName:__DEV__?{}:null, _isCustomAttributeFunctions:[], isCustomAttribute:function(attributeName){ for(var i=0;i=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 '+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];}}} 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){ var cleanComponents={}; var dirtyLeafIDs=Object.keys(measurement.writes); var allIDs=assign({},measurement.exclusive,measurement.inclusive); for(var id in allIDs){ var isDirty=false; for(var i=0;i0){ cleanComponents[id]=true;}} return cleanComponents;} var ReactDefaultPerfAnalysis={ getExclusiveSummary:getExclusiveSummary, getInclusiveSummary:getInclusiveSummary, getDOMSummary:getDOMSummary, getTotalTime:getTotalTime}; module.exports=ReactDefaultPerfAnalysis; }); __d('ReactMount',function(global, require, module, exports) { '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('emptyObject'); var containsNode=require('containsNode'); var instantiateReactComponent=require('instantiateReactComponent'); var invariant=require('invariant'); var setInnerHTML=require('setInnerHTML'); var shouldUpdateReactComponent=require('shouldUpdateReactComponent'); var validateDOMNesting=require('validateDOMNesting'); var warning=require('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); var instancesByReactRootID={}; var containersByReactRootID={}; if(__DEV__){ var rootElementsByReactRootID={};} var findComponentRootReusableArray=[]; function firstDifferenceIndex(string1,string2){ var minLen=Math.min(string1.length,string2.length); for(var i=0;i when using tables, nesting tags '+ 'like
,

, or , or using non-SVG elements in an '+ 'parent. '+ 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode));}, _mountImageIntoNode:function( markup, container, shouldReuseMarkup, transaction) { invariant( container&&( container.nodeType===ELEMENT_NODE_TYPE|| container.nodeType===DOC_NODE_TYPE|| container.nodeType===DOCUMENT_FRAGMENT_NODE_TYPE), 'mountComponentIntoNode(...): Target container is not valid.'); 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(__DEV__){ 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); invariant( container.nodeType!==DOC_NODE_TYPE, 'You\'re trying to render a component to the document using '+ 'server rendering but the checksum was invalid. This usually '+ 'means you rendered a different component type or props on '+ 'the client from the one on the server, or your render() '+ 'methods are impure. React cannot handle this case due to '+ 'cross-browser quirks by rendering at the document root. You '+ 'should look for environment dependent code in your components '+ 'and ensure the props are the same client and server side:\n%s', difference); if(__DEV__){ 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);}}} invariant( container.nodeType!==DOC_NODE_TYPE, 'You\'re trying to render a component to the document but '+ 'you didn\'t use server rendering. We can\'t do this '+ 'without using server rendering due to cross-browser quirks. '+ 'See ReactDOMServer.renderToString() for server rendering.'); if(transaction.useCreateElement){ while(container.lastChild){ container.removeChild(container.lastChild);} container.appendChild(markup);}else { setInnerHTML(container,markup);}}, ownerDocumentContextKey:ownerDocumentContextKey, 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; }); __d('ReactBrowserEventEmitter',function(global, require, module, exports) { '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'); var alreadyListeningTo={}; var isMonitoringScrollValue=false; var reactTopListenersCounter=0; 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'}; var topListenersIDKey='_reactListenersID'+String(Math.random()).slice(2); function getListeningForDocument(mountAt){ if(!Object.prototype.hasOwnProperty.call(mountAt,topListenersIDKey)){ mountAt[topListenersIDKey]=reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]]={};} return alreadyListeningTo[mountAt[topListenersIDKey]];} var ReactBrowserEventEmitter=assign({},ReactEventEmitterMixin,{ ReactEventListener:null, injection:{ injectReactEventListener:function(ReactEventListener){ ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener=ReactEventListener;}}, setEnabled:function(enabled){ if(ReactBrowserEventEmitter.ReactEventListener){ ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);}}, isEnabled:function(){ return !!( ReactBrowserEventEmitter.ReactEventListener&& ReactBrowserEventEmitter.ReactEventListener.isEnabled());}, 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/; var ReactMarkupChecksum={ CHECKSUM_ATTR_NAME:'data-react-checksum', addChecksumToMarkup:function(markup){ var checksum=adler32(markup); return markup.replace( TAG_END, ' '+ReactMarkupChecksum.CHECKSUM_ATTR_NAME+'="'+checksum+'"$&');}, 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; }); __d('adler32',function(global, require, module, exports) { 'use strict'; var MOD=65521; function adler32(data){ var a=1; var b=0; var i=0; var l=data.length; var m=l&~0x3; while(i]/; var setInnerHTML=function(node,html){ node.innerHTML=html;}; if(typeof MSApp!=='undefined'&&MSApp.execUnsafeLocalFunction){ setInnerHTML=function(node,html){ MSApp.execUnsafeLocalFunction(function(){ node.innerHTML=html;});};} if(ExecutionEnvironment.canUseDOM){ var testElement=document.createElement('div'); testElement.innerHTML=' '; if(testElement.innerHTML===''){ setInnerHTML=function(node,html){ if(node.parentNode){ node.parentNode.replaceChild(node,node);} if(WHITESPACE_TEST.test(html)|| html[0]==='<'&&NONVISIBLE_TEST.test(html)){ node.innerHTML=String.fromCharCode(0xFEFF)+html; var textNode=node.firstChild; if(textNode.data.length===1){ node.removeChild(textNode);}else { textNode.deleteData(0,1);}}else { node.innerHTML=html;}};}} module.exports=setInnerHTML; }); __d('validateDOMNesting',function(global, require, module, exports) { 'use strict'; var assign=require('Object.assign'); var emptyFunction=require('emptyFunction'); var warning=require('warning'); var validateDOMNesting=emptyFunction; if(__DEV__){ 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']; var inScopeTags=[ 'applet','caption','html','table','td','th','marquee','object', 'template', 'foreignObject','desc','title']; var buttonScopeTags=inScopeTags.concat(['button']); 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;} 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;}; var isTagValidWithParent=function(tag,parentTag){ switch(parentTag){ case 'select': return tag==='option'||tag==='optgroup'||tag==='#text'; case 'optgroup': return tag==='option'||tag==='#text'; case 'option': return tag==='#text'; case 'tr': return ( tag==='th'||tag==='td'||tag==='style'||tag==='script'|| tag==='template'); case 'tbody': case 'thead': case 'tfoot': return ( tag==='tr'||tag==='style'||tag==='script'|| tag==='template'); case 'colgroup': return tag==='col'||tag==='template'; case 'table': return ( tag==='caption'||tag==='colgroup'||tag==='tbody'|| tag==='tfoot'||tag==='thead'||tag==='style'|| tag==='script'||tag==='template'); 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'); case 'html': return tag==='head'||tag==='body';} 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': return parentTag==null;} return true;}; 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': return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope;} return null;}; var findOwnerStack=function(instance){ if(!instance){ return [];} var stack=[]; do { stack.push(instance);}while( instance=instance._currentElement._owner); stack.reverse(); return stack;}; var didWarn={}; validateDOMNesting=function(childTag,childInstance,ancestorInfo){ ancestorInfo=ancestorInfo||emptyAncestorInfo; var parentInfo=ancestorInfo.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 '); 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 to your code to match the DOM tree generated by '+ 'the browser.';} warning( false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. '+ 'See %s.%s', childTag, ancestorTag, ownerInfo, info);}else { warning( false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of '+ '<%s>. See %s.', childTag, ancestorTag, ownerInfo);}}}; validateDOMNesting.ancestorInfoContextKey= '__validateDOMNesting_ancestorInfo$'+Math.random().toString(36).slice(2); validateDOMNesting.updatedAncestorInfo=updatedAncestorInfo; 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; }); __d('AppStateIOS',function(global, require, module, exports) { 'use strict'; var Map=require('Map'); var NativeModules=require('NativeModules'); var RCTDeviceEventEmitter=require('RCTDeviceEventEmitter'); var RCTAppState=NativeModules.AppState; var logError=require('logError'); var invariant=require('invariant'); var _eventHandlers={ change:new Map(), memoryWarning:new Map()}; var AppStateIOS={ addEventListener:function( type, handler) { invariant( ['change','memoryWarning'].indexOf(type)!==-1, 'Trying to subscribe to unknown event: "%s"',type); if(type==='change'){ _eventHandlers[type].set(handler,RCTDeviceEventEmitter.addListener( 'appStateDidChange', function(appStateData){ handler(appStateData.app_state);}));}else if(type==='memoryWarning'){ _eventHandlers[type].set(handler,RCTDeviceEventEmitter.addListener( 'memoryWarning', handler));}}, removeEventListener:function( type, handler) { invariant( ['change','memoryWarning'].indexOf(type)!==-1, 'Trying to remove listener for unknown event: "%s"',type); if(!_eventHandlers[type].has(handler)){ return;} _eventHandlers[type].get(handler).remove(); _eventHandlers[type].delete(handler);}, currentState:'active'}; RCTDeviceEventEmitter.addListener( 'appStateDidChange', function(appStateData){ AppStateIOS.currentState=appStateData.app_state;}); RCTAppState.getCurrentAppState( function(appStateData){ AppStateIOS.currentState=appStateData.app_state;}, logError); module.exports=AppStateIOS; }); __d('AsyncStorage',function(global, require, module, exports) { 'use strict'; var NativeModules=require('NativeModules'); var RCTAsyncSQLiteStorage=NativeModules.AsyncSQLiteDBStorage; var RCTAsyncRocksDBStorage=NativeModules.AsyncRocksDBStorage; var RCTAsyncFileStorage=NativeModules.AsyncLocalStorage; var RCTAsyncStorage=RCTAsyncRocksDBStorage||RCTAsyncSQLiteStorage||RCTAsyncFileStorage; var AsyncStorage={ getItem:function( key, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiGet([key],function(errors,result){ var value=result&&result[0]&&result[0][1]?result[0][1]:null; var errs=convertErrors(errors); callback&&callback(errs&&errs[0],value); if(errs){ reject(errs[0]);}else { resolve(value);}});});}, setItem:function( key, value, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiSet([[key,value]],function(errors){ var errs=convertErrors(errors); callback&&callback(errs&&errs[0]); if(errs){ reject(errs[0]);}else { resolve(null);}});});}, removeItem:function( key, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiRemove([key],function(errors){ var errs=convertErrors(errors); callback&&callback(errs&&errs[0]); if(errs){ reject(errs[0]);}else { resolve(null);}});});}, mergeItem:function( key, value, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiMerge([[key,value]],function(errors){ var errs=convertErrors(errors); callback&&callback(errs&&errs[0]); if(errs){ reject(errs[0]);}else { resolve(null);}});});}, clear:function(callback){ return new Promise(function(resolve,reject){ RCTAsyncStorage.clear(function(error){ callback&&callback(convertError(error)); if(error&&convertError(error)){ reject(convertError(error));}else { resolve(null);}});});}, getAllKeys:function(callback){ return new Promise(function(resolve,reject){ RCTAsyncStorage.getAllKeys(function(error,keys){ callback&&callback(convertError(error),keys); if(error){ reject(convertError(error));}else { resolve(keys);}});});}, multiGet:function( keys, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiGet(keys,function(errors,result){ var error=convertErrors(errors); callback&&callback(error,result); if(error){ reject(error);}else { resolve(result);}});});}, multiSet:function( keyValuePairs, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiSet(keyValuePairs,function(errors){ var error=convertErrors(errors); callback&&callback(error); if(error){ reject(error);}else { resolve(null);}});});}, multiRemove:function( keys, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiRemove(keys,function(errors){ var error=convertErrors(errors); callback&&callback(error); if(error){ reject(error);}else { resolve(null);}});});}, multiMerge:function( keyValuePairs, callback) { return new Promise(function(resolve,reject){ RCTAsyncStorage.multiMerge(keyValuePairs,function(errors){ var error=convertErrors(errors); callback&&callback(error); if(error){ reject(error);}else { resolve(null);}});});}}; if(!RCTAsyncStorage.multiMerge){ delete AsyncStorage.mergeItem; delete AsyncStorage.multiMerge;} function convertErrors(errs){ if(!errs){ return null;} return (Array.isArray(errs)?errs:[errs]).map(function(e){return convertError(e);});} function convertError(error){ if(!error){ return null;} var out=new Error(error.message); out.key=error.key; return out;} module.exports=AsyncStorage; }); __d('BackAndroid',function(global, require, module, exports) { 'use strict'; function emptyFunction(){} var BackAndroid={ exitApp:emptyFunction, addEventListener:emptyFunction, removeEventListener:emptyFunction}; module.exports=BackAndroid; }); __d('CameraRoll',function(global, require, module, exports) { 'use strict'; var ReactPropTypes=require('ReactPropTypes'); var RCTCameraRollManager=require('NativeModules').CameraRollManager; var createStrictShapeTypeChecker=require('createStrictShapeTypeChecker'); var deepFreezeAndThrowOnMutationInDev= require('deepFreezeAndThrowOnMutationInDev'); var invariant=require('invariant'); var GROUP_TYPES_OPTIONS=[ 'Album', 'All', 'Event', 'Faces', 'Library', 'PhotoStream', 'SavedPhotos']; var ASSET_TYPE_OPTIONS=[ 'All', 'Videos', 'Photos']; deepFreezeAndThrowOnMutationInDev(GROUP_TYPES_OPTIONS); deepFreezeAndThrowOnMutationInDev(ASSET_TYPE_OPTIONS); var getPhotosParamChecker=createStrictShapeTypeChecker({ first:ReactPropTypes.number.isRequired, after:ReactPropTypes.string, groupTypes:ReactPropTypes.oneOf(GROUP_TYPES_OPTIONS), groupName:ReactPropTypes.string, assetType:ReactPropTypes.oneOf(ASSET_TYPE_OPTIONS), mimeTypes:ReactPropTypes.arrayOf(ReactPropTypes.string)}); var getPhotosReturnChecker=createStrictShapeTypeChecker({ edges:ReactPropTypes.arrayOf(createStrictShapeTypeChecker({ node:createStrictShapeTypeChecker({ type:ReactPropTypes.string.isRequired, group_name:ReactPropTypes.string.isRequired, image:createStrictShapeTypeChecker({ uri:ReactPropTypes.string.isRequired, height:ReactPropTypes.number.isRequired, width:ReactPropTypes.number.isRequired, isStored:ReactPropTypes.bool}). isRequired, timestamp:ReactPropTypes.number.isRequired, location:createStrictShapeTypeChecker({ latitude:ReactPropTypes.number, longitude:ReactPropTypes.number, altitude:ReactPropTypes.number, heading:ReactPropTypes.number, speed:ReactPropTypes.number})}). isRequired})). isRequired, page_info:createStrictShapeTypeChecker({ has_next_page:ReactPropTypes.bool.isRequired, start_cursor:ReactPropTypes.string, end_cursor:ReactPropTypes.string}). isRequired});var CameraRoll=(function(){function CameraRoll(){babelHelpers.classCallCheck(this,CameraRoll);}babelHelpers.createClass(CameraRoll,null,[{key:'saveImageWithTag',value:function saveImageWithTag( tag,successCallback,errorCallback){ invariant( typeof tag==='string', 'CameraRoll.saveImageWithTag tag must be a valid string.'); RCTCameraRollManager.saveImageWithTag( tag, function(imageTag){ successCallback&&successCallback(imageTag);}, function(errorMessage){ errorCallback&&errorCallback(errorMessage);});}},{key:'getPhotos',value:function getPhotos( params,callback,errorCallback){ var metaCallback=callback; if(__DEV__){ getPhotosParamChecker({params:params},'params','CameraRoll.getPhotos'); invariant( typeof callback==='function', 'CameraRoll.getPhotos callback must be a valid function.'); invariant( typeof errorCallback==='function', 'CameraRoll.getPhotos errorCallback must be a valid function.');} if(__DEV__){ metaCallback=function(response){ getPhotosReturnChecker( {response:response}, 'response', 'CameraRoll.getPhotos callback'); callback(response);};} RCTCameraRollManager.getPhotos(params,metaCallback,errorCallback);}}]);return CameraRoll;})(); CameraRoll.GroupTypesOptions=GROUP_TYPES_OPTIONS; CameraRoll.AssetTypeOptions=ASSET_TYPE_OPTIONS; module.exports=CameraRoll; }); __d('ImagePickerIOS',function(global, require, module, exports) { 'use strict'; var RCTImagePicker=require('NativeModules').ImagePickerIOS; var ImagePickerIOS={ canRecordVideos:function(callback){ return RCTImagePicker.canRecordVideos(callback);}, canUseCamera:function(callback){ return RCTImagePicker.canUseCamera(callback);}, openCameraDialog:function(config,successCallback,cancelCallback){ config=babelHelpers.extends({ videoMode:false}, config); return RCTImagePicker.openCameraDialog(config,successCallback,cancelCallback);}, openSelectDialog:function(config,successCallback,cancelCallback){ config=babelHelpers.extends({ showImages:true, showVideos:false}, config); return RCTImagePicker.openSelectDialog(config,successCallback,cancelCallback);}}; module.exports=ImagePickerIOS; }); __d('IntentAndroid',function(global, require, module, exports) { 'use strict'; module.exports={ openURI:function(url){ console.error('IntentAndroid is not supported on iOS');}}; }); __d('LayoutAnimation',function(global, require, module, exports) { 'use strict'; var PropTypes=require('ReactPropTypes'); var RCTUIManager=require('NativeModules').UIManager; var createStrictShapeTypeChecker=require('createStrictShapeTypeChecker'); var keyMirror=require('keyMirror'); var TypesEnum={ spring:true, linear:true, easeInEaseOut:true, easeIn:true, easeOut:true, keyboard:true}; var Types=keyMirror(TypesEnum); var PropertiesEnum={ opacity:true, scaleXY:true}; var Properties=keyMirror(PropertiesEnum); var animChecker=createStrictShapeTypeChecker({ duration:PropTypes.number, delay:PropTypes.number, springDamping:PropTypes.number, initialVelocity:PropTypes.number, type:PropTypes.oneOf( Object.keys(Types)), property:PropTypes.oneOf( Object.keys(Properties))}); var configChecker=createStrictShapeTypeChecker({ duration:PropTypes.number.isRequired, create:animChecker, update:animChecker, delete:animChecker}); function configureNext(config,onAnimationDidEnd){ configChecker({config:config},'config','LayoutAnimation.configureNext'); RCTUIManager.configureNextLayoutAnimation( config,onAnimationDidEnd||function(){},function(){});} function create(duration,type,creationProp){ return { duration:duration, create:{ type:type, property:creationProp}, update:{ type:type}};} var Presets={ easeInEaseOut:create( 300,Types.easeInEaseOut,Properties.opacity), linear:create( 500,Types.linear,Properties.opacity), spring:{ duration:700, create:{ type:Types.linear, property:Properties.opacity}, update:{ type:Types.spring, springDamping:0.4}}}; var LayoutAnimation={ configureNext:configureNext, create:create, Types:Types, Properties:Properties, configChecker:configChecker, Presets:Presets, easeInEaseOut:configureNext.bind( null,Presets.easeInEaseOut), linear:configureNext.bind( null,Presets.linear), spring:configureNext.bind( null,Presets.spring)}; module.exports=LayoutAnimation; }); __d('LinkingIOS',function(global, require, module, exports) { 'use strict'; var RCTDeviceEventEmitter=require('RCTDeviceEventEmitter'); var RCTLinkingManager=require('NativeModules').LinkingManager; var Map=require('Map'); var invariant=require('invariant'); var _notifHandlers=new Map(); var _initialURL=RCTLinkingManager&& RCTLinkingManager.initialURL; var DEVICE_NOTIF_EVENT='openURL';var LinkingIOS=(function(){function LinkingIOS(){babelHelpers.classCallCheck(this,LinkingIOS);}babelHelpers.createClass(LinkingIOS,null,[{key:'addEventListener',value:function addEventListener( type,handler){ invariant( type==='url', 'LinkingIOS only supports `url` events'); var listener=RCTDeviceEventEmitter.addListener( DEVICE_NOTIF_EVENT, handler); _notifHandlers.set(handler,listener);}},{key:'removeEventListener',value:function removeEventListener( type,handler){ invariant( type==='url', 'LinkingIOS only supports `url` events'); var listener=_notifHandlers.get(handler); if(!listener){ return;} listener.remove(); _notifHandlers.delete(handler);}},{key:'openURL',value:function openURL( url){ invariant( typeof url==='string', 'Invalid url: should be a string'); RCTLinkingManager.openURL(url);}},{key:'canOpenURL',value:function canOpenURL( url,callback){ invariant( typeof url==='string', 'Invalid url: should be a string'); invariant( typeof callback==='function', 'A valid callback function is required'); RCTLinkingManager.canOpenURL(url,callback);}},{key:'popInitialURL',value:function popInitialURL() { var initialURL=_initialURL; _initialURL=null; return initialURL;}}]);return LinkingIOS;})(); module.exports=LinkingIOS; }); __d('NetInfo',function(global, require, module, exports) { 'use strict'; var Map=require('Map'); var NativeModules=require('NativeModules'); var Platform=require('Platform'); var RCTDeviceEventEmitter=require('RCTDeviceEventEmitter'); var RCTNetInfo=NativeModules.NetInfo; var DEVICE_REACHABILITY_EVENT='networkDidChange'; var _subscriptions=new Map(); if(Platform.OS==='ios'){ var _isConnected=function( reachability) { return reachability!=='none'&& reachability!=='unknown';};}else if(Platform.OS==='android'){ var _isConnected=function( connectionType) { return connectionType!=='NONE'&&connectionType!=='UNKNOWN';};} var _isConnectedSubscriptions=new Map(); var NetInfo={ addEventListener:function( eventName, handler) { var listener=RCTDeviceEventEmitter.addListener( DEVICE_REACHABILITY_EVENT, function(appStateData){ handler(appStateData.network_info);}); _subscriptions.set(handler,listener);}, removeEventListener:function( eventName, handler) { var listener=_subscriptions.get(handler); if(!listener){ return;} listener.remove(); _subscriptions.delete(handler);}, fetch:function(){ return new Promise(function(resolve,reject){ RCTNetInfo.getCurrentReachability( function(resp){ resolve(resp.network_info);}, reject);});}, isConnected:{ addEventListener:function( eventName, handler) { var listener=function(connection){ handler(_isConnected(connection));}; _isConnectedSubscriptions.set(handler,listener); NetInfo.addEventListener( eventName, listener);}, removeEventListener:function( eventName, handler) { var listener=_isConnectedSubscriptions.get(handler); NetInfo.removeEventListener( eventName, listener); _isConnectedSubscriptions.delete(handler);}, fetch:function(){ return NetInfo.fetch().then( function(connection){return _isConnected(connection);});}}, isConnectionMetered:{}}; if(Platform.OS==='android'){ NetInfo.isConnectionMetered=function(callback){ RCTNetInfo.isConnectionMetered(function(_isMetered){ callback(_isMetered);});};} module.exports=NetInfo; }); __d('PushNotificationIOS',function(global, require, module, exports) { 'use strict'; var Map=require('Map'); var RCTDeviceEventEmitter=require('RCTDeviceEventEmitter'); var RCTPushNotificationManager=require('NativeModules').PushNotificationManager; var invariant=require('invariant'); var _notifHandlers=new Map(); var _initialNotification=RCTPushNotificationManager&& RCTPushNotificationManager.initialNotification; var DEVICE_NOTIF_EVENT='remoteNotificationReceived'; var NOTIF_REGISTER_EVENT='remoteNotificationsRegistered';var PushNotificationIOS=(function(){babelHelpers.createClass(PushNotificationIOS,null,[{key:'presentLocalNotification',value:function presentLocalNotification( details){ RCTPushNotificationManager.presentLocalNotification(details);}},{key:'scheduleLocalNotification',value:function scheduleLocalNotification( details){ RCTPushNotificationManager.scheduleLocalNotification(details);}},{key:'cancelAllLocalNotifications',value:function cancelAllLocalNotifications() { RCTPushNotificationManager.cancelAllLocalNotifications();}},{key:'setApplicationIconBadgeNumber',value:function setApplicationIconBadgeNumber( number){ RCTPushNotificationManager.setApplicationIconBadgeNumber(number);}},{key:'getApplicationIconBadgeNumber',value:function getApplicationIconBadgeNumber( callback){ RCTPushNotificationManager.getApplicationIconBadgeNumber(callback);}},{key:'addEventListener',value:function addEventListener( type,handler){ invariant( type==='notification'||type==='register', 'PushNotificationIOS only supports `notification` and `register` events'); var listener; if(type==='notification'){ listener=RCTDeviceEventEmitter.addListener( DEVICE_NOTIF_EVENT, function(notifData){ handler(new PushNotificationIOS(notifData));});}else if(type==='register'){ listener=RCTDeviceEventEmitter.addListener( NOTIF_REGISTER_EVENT, function(registrationInfo){ handler(registrationInfo.deviceToken);});} _notifHandlers.set(handler,listener);}},{key:'requestPermissions',value:function requestPermissions( permissions) { var requestedPermissions={}; if(permissions){ requestedPermissions={ alert:!!permissions.alert, badge:!!permissions.badge, sound:!!permissions.sound};}else { requestedPermissions={ alert:true, badge:true, sound:true};} RCTPushNotificationManager.requestPermissions(requestedPermissions);}},{key:'abandonPermissions',value:function abandonPermissions() { RCTPushNotificationManager.abandonPermissions();}},{key:'checkPermissions',value:function checkPermissions( callback){ invariant( typeof callback==='function', 'Must provide a valid callback'); RCTPushNotificationManager.checkPermissions(callback);}},{key:'removeEventListener',value:function removeEventListener( type,handler){ invariant( type==='notification'||type==='register', 'PushNotificationIOS only supports `notification` and `register` events'); var listener=_notifHandlers.get(handler); if(!listener){ return;} listener.remove(); _notifHandlers.delete(handler);}},{key:'popInitialNotification',value:function popInitialNotification() { var initialNotification=_initialNotification&& new PushNotificationIOS(_initialNotification); _initialNotification=null; return initialNotification;}}]); function PushNotificationIOS(nativeNotif){var _this=this;babelHelpers.classCallCheck(this,PushNotificationIOS); this._data={}; Object.keys(nativeNotif).forEach(function(notifKey){ var notifVal=nativeNotif[notifKey]; if(notifKey==='aps'){ _this._alert=notifVal.alert; _this._sound=notifVal.sound; _this._badgeCount=notifVal.badge;}else { _this._data[notifKey]=notifVal;}});}babelHelpers.createClass(PushNotificationIOS,[{key:'getMessage',value:function getMessage() { return this._alert;}},{key:'getSound',value:function getSound() { return this._sound;}},{key:'getAlert',value:function getAlert() { return this._alert;}},{key:'getBadgeCount',value:function getBadgeCount() { return this._badgeCount;}},{key:'getData',value:function getData() { return this._data;}}]);return PushNotificationIOS;})(); module.exports=PushNotificationIOS; }); __d('Settings',function(global, require, module, exports) { 'use strict'; var RCTDeviceEventEmitter=require('RCTDeviceEventEmitter'); var RCTSettingsManager=require('NativeModules').SettingsManager; var invariant=require('invariant'); var subscriptions=[]; var Settings={ _settings:RCTSettingsManager&&RCTSettingsManager.settings, get:function(key){ return this._settings[key];}, set:function(settings){ this._settings=babelHelpers.extends(this._settings,settings); RCTSettingsManager.setValues(settings);}, watchKeys:function(keys,callback){ if(typeof keys==='string'){ keys=[keys];} invariant( Array.isArray(keys), 'keys should be a string or array of strings'); var sid=subscriptions.length; subscriptions.push({keys:keys,callback:callback}); return sid;}, clearWatch:function(watchId){ if(watchId1){ for(var ii=1;ii-1){ DOMTREE_BYCLASS[i].splice(DOMTREE_BYCLASS[i].indexOf(self),1);}});} this.handleEvent.call(this,{type:'unload'});}},{key:'render',value:function render() {var _this2=this; this.compatHTML(); if(({}).toString.call(this.props.children)=='[object String]'){ return ( React.createElement(TouchableWithoutFeedback,{onPress:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'click',reactEvent:e}));}}, React.createElement(View,babelHelpers.extends({ ref:'i1'}, this.props,{ onTouchStart:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchStart',reactEvent:e}));}, onTouchMove:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchMove',reactEvent:e}));}, onTouchEnd:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchEnd',reactEvent:e}));}, style:htmlCssParser.removeTextStyleFromViewStyle(this.htmlProps.style)}), React.createElement(Text,{style:TemplateFill({ color:null, fontFamily:null, fontSize:null, fontStyle:null, fontWeight:null, letterSpacing:null, textAlign:null, textDecorationLine:null, textDecorationStyle:null, textDecorationColor:null, writingDirection:null}, this.htmlProps.style)},this.props.children))));}else if(({}).toString.call(this.props.children)=='[object Array]'){ var htmlChildren=[]; var self=this; this.props.children.forEach(function(item,idx){ if(item){ if(({}).toString.call(item)=='[object String]'){ htmlChildren.push(React.createElement(Text,{style:TemplateFill({ color:null, fontFamily:null, fontSize:null, fontStyle:null, fontWeight:null, letterSpacing:null, textAlign:null, textDecorationLine:null, textDecorationStyle:null, textDecorationColor:null, writingDirection:null}, self.htmlProps.style),key:idx},item));}else { htmlChildren.push(item);}}}); return ( React.createElement(TouchableWithoutFeedback,{onPress:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'click',reactEvent:e}));}}, React.createElement(View,babelHelpers.extends({ ref:'i1'}, this.props,{ onTouchStart:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchStart',reactEvent:e}));}, onTouchMove:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchMove',reactEvent:e}));}, onTouchEnd:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchEnd',reactEvent:e}));}, style:htmlCssParser.removeTextStyleFromViewStyle(this.htmlProps.style)}),htmlChildren)));}else { return ( React.createElement(TouchableWithoutFeedback,{onPress:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'click',reactEvent:e}));}}, React.createElement(View,babelHelpers.extends({ ref:'i1'}, this.props,{ onTouchStart:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchStart',reactEvent:e}));}, onTouchMove:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchMove',reactEvent:e}));}, onTouchEnd:function(e){_this2.handleEvent.call(_this2,new DomEvent({type:'touchEnd',reactEvent:e}));}, style:htmlCssParser.removeTextStyleFromViewStyle(this.htmlProps.style)}), this.props.children)));}}},{key:'compatHTML',value:function compatHTML( conf){ var self=this; if(conf&&conf.isBubble==false){}else { this._walkAndBindParent();} this.htmlProps=this.htmlProps||{}; babelHelpers.extends(this.htmlProps,this.props); for(var e in this.eventHandle){ this.eventHandle[e]=[];} var watchEventArray=['click','touchStart','touchMove','touchEnd']; watchEventArray.forEach(function(w){ var fn=self.props['on'+w.capitalizeFirstLetter()]; if(fn){ self.addEventListener(w,fn);}}); this.htmlProps.style={ fontSize:window.STYLESHEET.baseFontSize}; this.htmlProps.className=[]; if(this.props.className){ var a=this.props.className.split(/\s+/); this.htmlProps.className=a.slice(); var self=this; a.forEach(function(i){ DOMTREE_BYCLASS[i]=DOMTREE_BYCLASS[i]||[]; if(DOMTREE_BYCLASS[i].indexOf(self)==-1){ DOMTREE_BYCLASS[i].push(self);} babelHelpers.extends(self.htmlProps.style,STYLESHEET['.'+i]); if(STYLESHEET['+.'+i]){ var css=STYLESHEET['+.'+i].inherit.slice(); var find=false; var par=self; var maxLoop=999; while(css.length&&(par=par.parentNode())&&maxLoop>0){ maxLoop--; var cur=css[css.length-1]; if(/^\./.test(cur)){ if(par.htmlProps.className.indexOf(cur.substring(1))>-1){ css.pop(); if(css.length==0){ find=true; break;}}}else if(/^#/.test(cur)){ if(par.props.id==cur.substring(1)){ css.pop(); if(css.length==0){ find=true; break;}}}else if(/^[A-Z]/.test(cur)){ if(par.tagName()==cur){ css.pop(); if(css.length==0){ find=true; break;}}}} if(find){ babelHelpers.extends(self.htmlProps.style,STYLESHEET['+.'+i].css);}}});} var allEnumClass=allEnum(this.htmlProps.className); function allEnum(a){ var re=[];var _loop=function(){ o(i,a,re,a[i]); function o(start,array,re,prefix){ for(var j=start+1;j1?1:0, hasChildren:true, size:{width:0,height:0}};}else { this.state={ hasChildren:false, size:{width:0,height:0}};}}},{key:'componentDidMount',value:function componentDidMount() { babelHelpers.get(Object.getPrototypeOf(Carousel.prototype),'componentDidMount',this)&&babelHelpers.get(Object.getPrototypeOf(Carousel.prototype),'componentDidMount',this).call(this); if(this.state.hasChildren){ this._setUpTimer();}}},{key:'_onScrollBegin',value:function _onScrollBegin( event){ this.clearTimeout(this.timer);}},{key:'_onScrollEnd',value:function _onScrollEnd( event){ this._setUpTimer(); var offset=babelHelpers.extends({},event.nativeEvent.contentOffset); var childrenCount=this.props.children.length, size=this.state.size; if(offset.x===0){ offset.x=childrenCount*size.width;}else if(offset.x==(childrenCount+1)*size.width){ offset.x=size.width;} this._calculateCurrentPage(offset.x); this.setState({contentOffset:offset});}},{key:'_onLayout',value:function _onLayout() { var self=this; this.refs.container.measure(function(x,y,w,h,px,py){ self.setState({ contentOffset:{x:w}, size:{width:w,height:h}});});}},{key:'_setUpTimer',value:function _setUpTimer() { if(this.props.autoplay&&this.props.children.length>1){ this.clearTimeout(this.timer); this.timer=this.setTimeout(this._animateNextPage,this.props.delay);}}},{key:'_animateNextPage',value:function _animateNextPage() { var k=this.state.currentPage; var size=this.state.size; k++; this.setState({currentPage:k}); this.refs.scrollView.scrollTo(0,k*size.width); this._setUpTimer();}},{key:'_calculateCurrentPage',value:function _calculateCurrentPage( offset){ var size=this.state.size; var page=Math.floor((offset-size.width/2)/size.width)+1; this.setState({currentPage:page});}},{key:'render',value:function render() {var _this2=this; var pages=[], contents, containerProps; var size=this.state.size; containerProps={ ref:'container', onLayout:this._onLayout.bind(this), style:[this.props.style]}; if(!this.state.hasChildren){ contents= React.createElement(Text,{style:{backgroundColor:'white'}},'You are supposed to add children inside Carousel');} var children=this.props.children; if(children.length>=1){ pages.push(children[children.length-1]);} for(var i=0;i=1){ pages.push(children[0]);} pages=pages.map(function(page,i){ return ( React.createElement(View,{ style:[{width:size.width,height:size.height},_this2.props.pageStyle], key:"page"+i},page));}); contents= React.createElement(ScrollView,{ ref:'scrollView', onScrollBeginDrag:this._onScrollBegin.bind(this), onMomentumScrollEnd:this._onScrollEnd.bind(this), alwaysBounceHorizontal:false, alwaysBounceVertical:false, contentInset:{top:0}, automaticallyAdjustContentInsets:false, showsHorizontalScrollIndicator:false, horizontal:true, pagingEnabled:true, bounces:false, contentOffset:this.state.contentOffset, contentContainerStyle:[ styles.horizontalScroll, this.props.contentContainerStyle, { width:size.width*(this.props.children.length+(this.props.children.length>1?2:0)), height:size.height}]}, pages); return ( React.createElement(View,containerProps, contents));}}]);return Carousel;})(Element); var styles=StyleSheet.create({ horizontalScroll:{ position:'absolute'}}); Carousel.propTypes={ children:React.PropTypes.node.isRequired, delay:React.PropTypes.number, style:View.propTypes.style, pageStyle:View.propTypes.style, contentContainerStyle:View.propTypes.style, autoplay:React.PropTypes.bool}; Carousel.defaultProps={ delay:PAGE_CHANGE_DELAY, autoplay:true}; module.exports=Carousel; }); ;require("InitializeJavaScriptAppEngine"); ;require("native/common/LightningStorm.js"); __SSTOKENSTRING = "@generated SignedSource<<55a77aae1a2905da58791de644adf2ca>>"; ================================================ FILE: build/part2.js ================================================ __d('native/index.js',function(global, require, module, exports) { window. IMG_CDN_PREFIX='http://10.32.184.134:5389/res/'; includeCSS("require('native/css/lightningStorm.js')"); var homepage=React.createClass({displayName:'homepage', render:function(){ return ( React.createElement(Navigator,{ initialRoute:{page:require('native/vsIndex.js')}, renderScene:function(route,navigator){ window.pageRoute=navigator; return React.createElement(route.page,babelHelpers.extends({navigator:navigator},route));}}));}}); if(isNative){ React.AppRegistry.registerComponent('native',function(){return homepage;});}else { React.render(React.createElement(homepage,null),document.body);} }); __d('native/css/lightningStorm.js',function(global, require, module, exports) { var styles={ ".native-header":{ "flexDirection":"row", "alignItems":"center", "justifyContent":"center", "height":"40pt", "color":"#ffffff", "backgroundColor":"rgb(9,159,222)"}, ".native-header-box":{ "flex":"1", "alignItems":"center", "justifyContent":"center"}, ".native-header-title":{ "color":"#ffffff"}, ".native-header-leftButton":{ "position":"absolute", "top":"0", "left":"10pt", "color":"black"}, ".native-header-rightButton":{ "position":"absolute", "right":"10pt", "top":"0", "backgroundColor":"white"}}; module.exports=styles; }); __d('native/vsIndex.js',function(global, require, module, exports) { includeCSS("require('native/css/vsIndex.js')");var vsIndex=(function(_Element){babelHelpers.inherits(vsIndex,_Element); function vsIndex(){babelHelpers.classCallCheck(this,vsIndex);var _this=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(vsIndex).call(this)); _this.state={ dataSource:SimpleListView.initDataSource()};return _this;}babelHelpers.createClass(vsIndex,[{key:"render",value:function render() { return ( React.createElement(Div,{style:{height:windowHeight}}, React.createElement(Header,{title:"维多利亚的秘密",leftButton:null}), React.createElement(Div,{id:"J-block-test",className:"j-j_j i_i-i"},"测试水平居中垂直居中"), React.createElement(SimpleListView,{className:"listPage-listView iiii",dataSource:this.state.dataSource, renderRow:this._renderRow})));}},{key:"componentDidMount",value:function componentDidMount() { var self=this; fetch('http://statics1.jiaru.club/react-native-example/list.js', {method:'get',headers:{'Content-Type':'application/json;charset=utf-8'}}). then(function(req){ req.json().then(function(res){ var o=self.state.dataSource.cloneWithRows(res.list); self.setState({ dataSource:o});});});}},{key:"_renderRow",value:function _renderRow( row,sid,rowid){ return React.createElement(Row,{data:arguments,jumpFn:this.jumpFn});}}]);return vsIndex;})(Element);var Row=(function(_Element2){babelHelpers.inherits(Row,_Element2); function Row(){babelHelpers.classCallCheck(this,Row);var _this2=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(Row).call(this)); _this2.state={ numberOfLines:3};return _this2;}babelHelpers.createClass(Row,[{key:"render",value:function render() { var row=this.props.data[0]; var rowid=this.props.data[2]; return ( React.createElement(Div,{className:"index-list-row"+(rowid%2==0?" index-list-complexRow":"")}, React.createElement(Div,{className:"index-list-leftImg",onClick:this.jumpImgList.bind(this)}, React.createElement(Img,{className:"index-list-leftImg-img",src:row.smallpic})), React.createElement(Div,{className:"index-list-rightBox"}, React.createElement(Span,{className:"index-list-rightBox-row"}, React.createElement(Span,null,"姓名:"), React.createElement(Span,null,row.name)), React.createElement(Div,{onClick:this.collapse.bind(this)}, React.createElement(Span,{ref:"J_r",numberOfLines:this.state.numberOfLines,className:"index-list-rightBox-row-desc"}, React.createElement(Span,null,"简介:"), React.createElement(Span,null,row.desc))))));}},{key:"collapse",value:function collapse() { if(this.state.numberOfLines==3){ this.setState({ numberOfLines:null});}else { this.setState({ numberOfLines:3});}}},{key:"jumpImgList",value:function jumpImgList() { pageRoute.push({ page:require('native/vsImgList.js'), a:1, b:2, c:3});}}]);return Row;})(Element); module.exports=vsIndex; }); __d('native/css/vsIndex.js',function(global, require, module, exports) { var styles={ "body":{ "margin":"0", "padding":"0"}, "#J-block-test":{ "backgroundColor":"yellow", "height":"2rem"}, ".j-j_j":{ "color":"red", "flexDirection":"row", "justifyContent":"center", "alignItems":"center"}, ".i_i-i":{ "color":"black"}, ".j-j_j.i_i-i":{ "color":"green"}, ".index-contains":{ "flex":"1", "alignItems":"center"}, ".index-goDiv":{ "flexDirection":"row", "alignItems":"center", "padding":"10", "justifyContent":"center"}, ".index-btn":{ "flex":"1", "alignItems":"center", "justifyContent":"center", "flexDirection":"row", "padding":"10pt"}, ".index-list-row .index-list-leftImg":{ "width":"3rem", "paddingTop":".5rem", "flexDirection":"row", "justifyContent":"center"}, ".index-list-leftImg-img":{ "width":"2rem", "height":"2rem"}, ".index-list-row":{ "flexDirection":"row", "justifyContent":"flex-start"}, ".index-list-row .index-list-rightBox":{ "flex":"1"}, ".index-list-row .index-list-rightBox-row-desc":{ "backgroundColor":"red"}, ".index-list-complexRow .index-list-rightBox .index-list-rightBox-row":{ "backgroundColor":"green", "color":"red"}, "#jjj":{ "backgroundColor":"green"}, "SimpleListView":{ "backgroundColor":"yellow"}}; module.exports=styles; }); __d('native/vsImgList.js',function(global, require, module, exports) { includeCSS("require('native/css/vsImgList.js')");var vsImgList=(function(_Element){babelHelpers.inherits(vsImgList,_Element); function vsImgList(passedArgs){babelHelpers.classCallCheck(this,vsImgList);var _this=babelHelpers.possibleConstructorReturn(this,Object.getPrototypeOf(vsImgList).call(this)); _this.state={ list:null, pageHeight:windowHeight}; _this.passedArgs={ a:passedArgs.a, b:passedArgs.b, c:passedArgs.c};return _this;}babelHelpers.createClass(vsImgList,[{key:'componentWillMount',value:function componentWillMount() { var self=this; fetch('http://statics1.jiaru.club/react-native-example/hesui.js', { method:'get', headers:{'Content-Type':'application/json;charset=utf-8'}}). then(function(req){ req.json().then(function(res){ self.setState({ list:res.images});});});}},{key:'render',value:function render() {var _this2=this; return ( React.createElement(Div,{className:'imgList'}, React.createElement(Header,{ref:'J_header',title:'照片秀',leftButton:{handler:this.backBtn}}), (function(){ if(_this2.state.list){ return ( React.createElement(Carousel,{style:{height:windowHeight-40}}, _this2.state.list.map(function(o,idx){ return ( React.createElement(Div,{key:idx,style:{width:windowWidth,height:windowHeight-40,alignItems:'center',justifyContent:'center'}}, React.createElement(Img,{src:o.img,style:{width:o.width,height:o.height}})));})));}else { return ( React.createElement(Div,{style:{backgroundColor:'#fffff',width:windowWidth,height:windowHeight-40,alignItems:'center',justifyContent:'center'}}, React.createElement(Span,null,'加载中...')));}}). call(this), React.createElement(Div,{className:'float-bg'},'这是一个透明浮层的测试,上一页面传递过来的参数为',JSON.stringify(this.passedArgs))));}},{key:'backBtn',value:function backBtn() { pageRoute.pop();}}]);return vsImgList;})(Element); module.exports=vsImgList; }); __d('native/css/vsImgList.js',function(global, require, module, exports) { var styles={ ".imgList":{ "position":"relative"}, ".float-bg":{ "backgroundColor":"gray", "color":"#000000", "opacity":"0.2", "height":"4rem", "width":"100%", "position":"absolute", "bottom":"0", "left":"0"}}; module.exports=styles; }); ;require("native/index.js"); ================================================ FILE: css/cxylhl/index.css ================================================ body * { font-family:"Consolas","Microsoft Yahei", Arial, sans-serif; } body { background: white; margin: 0; padding: 0; } .header { flex-direction: row; } .sup { font-size: 0.4rem; background: yellow; color: red; } .container { } .container .title{ color: #bbb; font-weight: bold; background: #555; padding: 5px 15px; } .adlink { text-align: center; font-size: 11pt; } .adlink a { text-decoration: none; display:block; color: #666; font-weight: bold; margin-bottom: 10px; background: #eee; border: 1px solid #ddd; border-radius: 4px; padding: 10pt; margin-top: 10pt; } .date{ font-size:17pt; font-weight: bold; line-height: 30pt; text-align: center; } .split, .clear { clear: both; height: 1px; overflow-y: hidden; } .good, .bad { display: flex; flex-direction: row; } .bad { /*top: -1px;*/ } .good .title, .bad .title { flex: 0.5; font-weight: bold; font-size: 2rem; display: flex; } .good .title .title-text, .bad .title .title-text{ } .good { background: #ffee44; } .bad { background: #ff4444; } .good .title { background: #ffee44; align-self: center; text-align: center; } .good .content { background: #ffffaa; } .someday .good .title { background: #aaaaaa; } .bad .title { background: #ff4444; color: #fff; align-self: center; text-align: center; } .bad .content { background: #ffddd3; } .someday .bad .title { background: #666666; color: #fff; } .good .content, .bad .content { flex: 1; padding: 10px; } .someday .good { background: #dddddd; } .someday .bad { background: #aaaaaa; } .content .name { height: 1.5rem; justify-content: center; font-size: 1rem; font-weight: bold; color: #444; } .content .description { font-size: 0.7rem; font-weight: normal; color: #777; } .Divne-tip { padding: 10px; flex-direction: row; align-items: center; } .adDivnk { font-size: 0.5rem; } .direction_value { color:#4a4; font-weight: bold; } .someday .direction_value { color:#888; } .goddes_value { color: #f87; } .someday .goddes_value { color: #777; } .comment { font-size: 11pt; margin: 10px; color: #999; } .spDivt { font-size: 0.7rem; } ================================================ FILE: css/game/game2048.css ================================================ .container { padding: 0 20pt; } .heading { display: flex; height: 80pt; margin-top: 40pt; flex-direction: row; } .heading .heading-title { font-size: 48pt; color: #776E65; font-weight: bold; } .heading .scores { display: flex; flex: 1; flex-direction: row; justify-content: flex-end; flex-wrap: wrap; align-items: flex-start; } .heading .container { display: flex; background-color: #bbada0; padding-left: 15pt; padding-right: 15pt; padding-top: 5pt; padding-bottom: 5pt; border-radius: 3pt; margin-left: 5pt; flex-direction: column; align-items: center; } .heading .container-title { color: #eee4da; text-align: center; font-weight: bold; font-size: 12pt; } .heading .container-value { color: #fff; text-align: center; font-size: 24pt; font-weight: bold; } .abovegame { display: flex; flex-direction: row; flex-wrap: nowrap; margin-top: 5pt; } .abovegame .textContainer { display: flex; flex: 1; margin-right: 10pt; } .abovegame .text { color: #776E65; font-size: 16pt; line-height: 26pt; } .abovegame .boldText { font-weight: bold; } .abovegame .newGameContainer { background-color: #8f7a66; padding: 15pt 10pt; border-radius: 3pt; } ================================================ FILE: css/jqueryapi.css ================================================ .cls1 { color: red; } .cls2 { color: yellow; } ================================================ FILE: css/lightningStorm.css ================================================ /** ** common/header **/ .custom-native-header { margin-top: 20pt; } .native-header { flex-direction: row; align-items: center; justify-content: center; height: 40pt; color: #ffffff; background-color: rgb(9,159,222); margin-top: 20pt; } .native-header-box { flex: 1; display: flex; align-items: center; justify-content: center; } .native-header-title { color: #ffffff; } .native-header-leftButton { position: absolute; top: 0; left: 10pt; color: black; } .native-header-rightButton { position: absolute; right: 10pt; top: 0; background-color: white; } ================================================ FILE: css/vsImgList.css ================================================ .imgList { position: relative; } .float-bg { background-color: gray; color: #000; opacity: 0.2; height: 4rem; width: 100%; position: absolute; bottom: 0; left: 0; } ================================================ FILE: css/vsIndex.css ================================================ /** ** base **/ body { margin: 0; padding: 0; } /** ** index **/ #J-block-test { background-color: yellow; height: 2rem; } .j-j_j { display: flex; color: red; flex-direction: row; justify-content: center; align-items: center; } .i_i-i { color: black; } .j-j_j.i_i-i { color: green; } .index-contains { flex: 1; align-items: center; } .index-goDiv { display: flex; flex-direction: row; alignItems: center; padding: 10; justify-content: center; } .index-btn { display: flex; flex: 1; align-items: center; justify-content: center; flex-direction: row; padding: 10pt; } .index-list-row .index-list-leftImg { width: 3rem; display: flex; padding-top: .5rem; flex-direction: row; justify-content: center; } .index-list-leftImg-img{ width: 2rem; height: 2rem; } .index-list-row { display: flex; flex-direction: row; justify-content: flex-start; } .index-list-row .index-list-rightBox { flex: 1; } .index-list-row .index-list-rightBox-row-desc { background-color: red; } .index-list-complexRow .index-list-rightBox .index-list-rightBox-row { background-color: green; color: red; } #jjj { background-color: green; } SimpleListView { background-color: yellow; } ================================================ FILE: dev.sh ================================================ #!/bin/sh osascript < -1 || // imageStyle.indexOf(p) > -1 || textStyle.indexOf(p) > -1// || flexboxStyle .indexOf(p) > -1 || transformStyle .indexOf(p) > -1) { obj[p] = self.reverseCssValue(re[p]); } } } else if (viewStyle.indexOf(k) > -1 || // imageStyle.indexOf(k) > -1 || textStyle.indexOf(k) > -1// || flexboxStyle.indexOf(k) > -1 || transformStyle.indexOf(k) > -1) { obj[k] = self.reverseCssValue(declaration.value); } } } }); rule.selectors.forEach(function(selector) { var name = self.nameGenerator(selector.trim()); if(name in result){ Object.assign(result[name], obj); }else{ result[name] = Object.assign({}, obj);; } }); } }); } nativeCSS.prototype.isShortCut = function(k, v) { if (/^border(Top|Left|Bottom|Right|)$/.test(k)) { var a = v.split(/\s+/); return true; } else if (/^(margin|padding)$/.test(k)) { var a = v.split(/\s+/); if (a.length > 1) { return true; } } else if (/^(borderRadius)$/.test(k)) { var a = v.split(/\s+/); if (a.length > 1) { return true; } } return false; } nativeCSS.prototype.reverseShortCut = function(k, v) { var re = {}; if (/^border(Top|Left|Bottom|Right|)$/.test(k)) { var a = v.split(/\s+/); if (a.length == 3) { var k1 = k.match(/^border(Top|Left|Bottom|Right|)$/)[0]; re[k1 + 'Width'] = a[0]; re[k1 + 'Style'] = a[1]; re[k1 + 'Color'] = a[2]; }else if(a.length == 1){ var k1 = k.match(/^border(Top|Left|Bottom|Right|)$/)[0]; re[k1 + 'Width'] = a[0] == 'none' ? 0 : a[0]; } } else if (/^(margin|padding)$/.test(k)) { var a = v.split(/\s+/); var k1 = k.match(/^(margin|padding)$/)[0]; if (a.length == 4) { re[k1 + 'Top'] = a[0]; re[k1 + 'Right'] = a[1]; re[k1 + 'Bottom'] = a[2]; re[k1 + 'Left'] = a[3]; } else if (a.length == 3) { re[k1 + 'Top'] = a[0]; re[k1 + 'Right'] = a[1]; re[k1 + 'Left'] = a[1]; re[k1 + 'Bottom'] = a[2]; } else if (a.length == 2) { re[k1 + 'Top'] = a[0]; re[k1 + 'Bottom'] = a[0]; re[k1 + 'Right'] = a[1]; re[k1 + 'Left'] = a[1]; } } else if (/^(borderRadius)$/.test(k)) { var a = v.split(/\s+/); var k1 = 'border', k11 = 'Radius'; if (a.length == 4) { re[k1 + 'TopLeft' + k11] = a[0]; re[k1 + 'TopRight' + k11] = a[1]; re[k1 + 'BottomRight' + k11] = a[2]; re[k1 + 'BottomLeft' + k11] = a[3]; } else if (a.length == 3) { re[k1 + 'TopLeft' + k11] = a[0]; re[k1 + 'TopRight' + k11] = a[1]; re[k1 + 'BottomLeft' + k11] = a[1]; re[k1 + 'BottomRight'] = a[2]; } else if (a.length == 2) { re[k1 + 'TopLeft' + k11] = a[0]; re[k1 + 'TopRight' + k11] = a[0]; re[k1 + 'Right' + k11] = a[1]; re[k1 + 'BottomLeft' + k11] = a[1]; } } return re; } nativeCSS.prototype.reverseCssValue = function(v){ // if(/^#([0-9a-fA-F]{3})$/.test(v)){ var t = v.match(/^#([0-9a-fA-F]{3})$/)[1]; v = '#' + t +t; } return v; // } nativeCSS.prototype.transform = function(css) { var result = {}; transformRules(this, css.stylesheet.rules, result); return result; } nativeCSS.prototype.convert = function(cssFile) { var path = process.cwd() + '/' + cssFile; if (!(require('fs').existsSync(path))) return 'Ooops!\nError: CSS file not found!'; var self = this, css = src.readFile(path); css = cssParser.parse(css, { silent : false, source : path }); return self.transform(css); } nativeCSS.prototype.generateFile = function(obj, where, react) { if (!where || where.indexOf('--') > -1) return console.log('Please, set a output path!'); var self = this, body; where = process.cwd() + '/' + where; if (react) { src.writeFile(where, 'var styles = StyleSheet.create(\n'); body = self.indentObject(obj, 2); src.appendFile(where, body + '\n);'); return; } src.writeFile(where, 'var styles = '); body = self.indentObject(obj, 2); src.appendFile(where, body + '\nmodule.exports = styles;'); } module.exports = new nativeCSS(); ================================================ FILE: package.json ================================================ { "devDependencies": { "babel-core": "^6.3.26", "babel-loader": "^6.2.1", "babel-plugin-syntax-async-functions": "^6.3.13", "babel-plugin-transform-async-to-generator": "^6.3.13", "babel-plugin-transform-object-assign": "^6.3.13", "babel-plugin-transform-regenerator": "^6.3.26", "babel-plugin-transform-runtime": "^6.3.13", "babel-polyfill": "^6.3.14", "babel-preset-es2015": "^6.3.13", "babel-preset-react": "^6.3.13", "babel-preset-stage-0": "^6.3.13", "chokidar": "^1.4.2", "css": "^2.2.1", "domkit": "0.0.1", "fbjs": "^0.6.1", "webpack": "^1.12.9" }, "dependencies": { "babel-polyfill": "^6.3.14", "mkdirp": "^0.5.1" } } ================================================ FILE: react-native.js.split.build.js ================================================ /** * 这个文件用来上线的时候实现reactnative的打包分拆,part1类似框架部分,part2是业务部分的代码 */ var process = require('child_process'); var fs = require('fs'); //直接调用命令 var cmd1 = 'cd reactnative;react-native bundle --platform ios --entry-file ./common/LightningStorm.js --bundle-output ../build/part1.js'; process.exec(cmd1, function (error, stdout, stderr){ console.log(cmd1); console.log(stdout); console.log(stderr); if (error !== null) { console.log('exec error: ' + error); } //step2 var cmd2 = 'cd reactnative;react-native bundle --platform ios --entry-file index.ios.js --bundle-output ../build/part2.js'; process.exec(cmd2, function (error, stdout, stderr){ console.log(cmd2); console.log(stdout); console.log(stderr); if (error !== null) { console.log('exec error: ' + error); } var data = fs.readFileSync('./build/part2.js'); fs.writeFileSync('./build/part2.js',data.toString().match(/__d\('native\/index.(.|\r|\n)+(?=__SSTOKENSTRING)/gm)[0].replace(/;\w+\("InitializeJavaScriptAppEngine"\);/,'')); }); }); ================================================ FILE: react.css.build.js ================================================ var fs = require('fs'); var nativeCSS = require('./native-css'); var mkdirp = require('mkdirp'); var fileList = []; function walk(path) { var dirList = fs.readdirSync(path); dirList.forEach(function(item) { if (fs.statSync(path + '/' + item).isDirectory()) { walk(path + '/' + item + '/'); } else { fileList.push(path + item); } }); } walk('./css/'); console.log(fileList); fileList.forEach(function(f){ if(/\.css$/i.test(f)){ transformCSS(f); } }); watch(); function watch(){ var chokidar = require('chokidar'); try{ var r = chokidar.watch('./css/').on('change',function(fileName){ fileName = './' + fileName; console.log('检测到' + fileName + '有change'); try{ if(/\.css$/i.test(fileName)){ transformCSS(fileName); } }catch(e){ console.log(e); } }) }catch(e){} console.log('start watching!'); } function transformCSS(fileName){ var cssObject = nativeCSS.convert(fileName); var newFileName = fileName.replace('/css/','/reactnative/css/').replace(/\.css$/,'.js'); console.log(newFileName); var dir = newFileName.match(/(\..+\/)/)[0]; mkdirp.sync(dir); console.log('build '+newFileName); nativeCSS.generateFile(cssObject, newFileName, false); } ================================================ FILE: reactnative/2048/components/aboveGame.js ================================================ class AboveGame extends Element { render(){ return (

); } } module.exports = AboveGame; ================================================ FILE: reactnative/2048/components/container.js ================================================ includeCSS("require('../../css/game/game2048')") // Views var Heading = require('./heading'); var AboveGame = require('./aboveGame'); var GameContainer = require('./gameContainer'); // Modules //var TouchManager = require('../utils/touchManager'); var StorageManager = require('../utils/localStorageManager'); var Grid = require('../utils/grid'); var Tile = require('../utils/tile'); // StorageManager var storageManager = new StorageManager(); class Container extends Element{ componentWillMount(){ this.setup(); this.moving = false; } _handlePanResponderGrant(e: Object) { if(this.moving==false){ this.moving = true; this.touchStartState = { pageX: e.changedTouches[0].pageX, pageY: e.changedTouches[0].pageY } } } _handlePanResponderEnd(e: Object) { console.debug(arguments) if(this.moving && this.touchStartState != null){ this.moving = false; var dx = e.changedTouches[0].pageX - this.touchStartState.pageX; var dy = e.changedTouches[0].pageY - this.touchStartState.pageY; var absDx = dx>0?dx:-dx; var absDy = dy>0?dy:-dy; var canMove = absDx>absDy?absDx-absDy>10:absDx-absDy<-10; if (canMove) { // (right : left) : (down : up) this.move(absDx > absDy ? (dx > 0 ? 1 : 3) : (dy > 0 ? 2 : 0)); } this.touchStartState = null; } } render(){ var tiles = this.state.tiles?this.state.tiles:[]; return (
) } getRandomTiles() { var ret = []; for (var i = 0; i < this.props.startTiles; i++) { ret.push(this.getRandomTile()) } return ret; } getRandomTile() { var value = Math.random() < 0.9 ? 2 : 4; var pos = this.grid.randomAvailableCell(); var tile = new Tile(pos, value); this.grid.insertTile(tile); return { value: value, x: pos.x, y: pos.y, prog: tile.prog }; } continueGame() { this.won = false; this.over = false; this.setState({won: this.won, over: this.over}); } restart() { storageManager.clearGameState(); this.continueGame(); // Clear the game won/lost message this.setup(); } // Keep playing after winning (allows going over 2048) keepGoing() { this.keepPlaying = true; this.continueGame(); // Clear the game won/lost message } // Return true if the game is lost, or has won and the user hasn't kept playing isGameTerminated() { return this.over || (this.won && !this.keepPlaying); } // Set up the game async setup() { var previousState = await storageManager.getGameState(); // Reload the game from a previous game if present if (previousState) { this.grid = new Grid(previousState.grid.size, previousState.grid.cells); // Reload grid this.score = parseInt(previousState.score); this.over = (previousState.over== true || previousState.over=='true'); this.won = (previousState.won== true || previousState.won=='true'); this.keepPlaying = (previousState.keepPlaying== true || previousState.keepPlaying=='true'); } else { this.grid = new Grid(this.props.size); this.score = 0; this.over = false; this.won = false; this.keepPlaying = false; } this.setState({score: this.score, best: parseInt(await storageManager.getBestScore()), tiles: this.getRandomTiles(), over: this.over, won: this.won}); } // Set up the initial tiles to start the game with addStartTiles() { for (var i = 0; i < this.startTiles; i++) { this.addRandomTile(); } } // Adds a tile in a random position addRandomTile() { var cellsAvailable = this.grid.cellsAvailable(); if (cellsAvailable) { var value = Math.random() < 0.9 ? 2 : 4; var tile = new Tile(this.grid.randomAvailableCell(), value); this.grid.insertTile(tile); } } // Sends the updated grid to the actuator async actuate() { // Clear the state when the game is over (game over only, not win) if (this.over) { await storageManager.clearGameState(); } else { await storageManager.setGameState(this.serialize()); } // this.actuator.actuate(this.grid, { // score: this.score, // over: this.over, // won: this.won, // bestScore: storageManager.getBestScore(), // terminated: this.isGameTerminated() // }); var tiles = []; this.grid.cells.forEach(function (column) { column.forEach(function (cell) { if (cell) { tiles.push({ x: cell.x, y: cell.y, value: cell.value, prog: cell.prog }); } }); }); var bestScore = parseInt(storageManager.getBestScore()); if (bestScore < this.score) { await storageManager.setBestScore(this.score); this.setState({score: this.score, best: this.score, tiles: tiles, won: this.won, over:this.over}); } else { this.setState({score: this.score, tiles: tiles, won: this.won, over:this.over}); } } // Represent the current game as an object serialize() { return { grid: this.grid.serialize(), score: this.score, over: this.over, won: this.won, keepPlaying: this.keepPlaying }; } // Save all tile positions and remove merger info prepareTiles() { this.grid.eachCell(function (x, y, tile) { if (tile) { tile.mergedFrom = null; tile.savePosition(); } }); } // Move a tile and its representation moveTile(tile, cell) { this.grid.cells[tile.x][tile.y] = null; this.grid.cells[cell.x][cell.y] = tile; tile.updatePosition(cell); } // Move tiles on the grid in the specified direction move(direction) { // 0: up, 1: right, 2: down, 3: left var self = this; if (this.isGameTerminated()) return; // Don't do anything if the game's over var cell, tile; var vector = this.getVector(direction); var traversals = this.buildTraversals(vector); var moved = false; // Save the current tile positions and remove merger information this.prepareTiles(); // Traverse the grid in the right direction and move tiles traversals.x.forEach(function (x) { traversals.y.forEach(function (y) { cell = { x: x, y: y }; tile = self.grid.cellContent(cell); if (tile) { var positions = self.findFarthestPosition(cell, vector); var next = self.grid.cellContent(positions.next); // Only one merger per row traversal? if (next && next.value === tile.value && !next.mergedFrom) { var merged = new Tile(positions.next, tile.value * 2); merged.mergedFrom = [tile, next]; self.grid.insertTile(merged); self.grid.removeTile(tile); // Converge the two tiles' positions tile.updatePosition(positions.next); // Update the score self.score += merged.value; // The mighty 2048 tile if (merged.value === 2048) self.won = true; } else { self.moveTile(tile, positions.farthest); } if (!self.positionsEqual(cell, tile)) { moved = true; // The tile moved from its original cell! } } }); }); if (moved) { this.addRandomTile(); if (!this.movesAvailable()) { this.over = true; // Game over! } this.actuate(); } } // Get the vector representing the chosen direction getVector(direction) { // Vectors representing tile movement var map = { 0: { x: 0, y: -1 }, // Up 1: { x: 1, y: 0 }, // Right 2: { x: 0, y: 1 }, // Down 3: { x: -1, y: 0 } // Left }; return map[direction]; } // Build a list of positions to traverse in the right order buildTraversals(vector) { var traversals = { x: [], y: [] }; for (var pos = 0; pos < this.props.size; pos++) { traversals.x.push(pos); traversals.y.push(pos); } // Always traverse from the farthest cell in the chosen direction if (vector.x === 1) traversals.x = traversals.x.reverse(); if (vector.y === 1) traversals.y = traversals.y.reverse(); return traversals; } findFarthestPosition(cell, vector) { var previous; // Progress towards the vector direction until an obstacle is found do { previous = cell; cell = { x: previous.x + vector.x, y: previous.y + vector.y }; } while (this.grid.withinBounds(cell) && this.grid.cellAvailable(cell)); return { farthest: previous, next: cell // Used to check if a merge is required }; } movesAvailable() { return this.grid.cellsAvailable() || this.tileMatchesAvailable(); } // Check for available matches between tiles (more expensive check) tileMatchesAvailable () { var self = this; var tile; for (var x = 0; x < this.props.size; x++) { for (var y = 0; y < this.props.size; y++) { tile = this.grid.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { x: x + vector.x, y: y + vector.y }; var other = self.grid.cellContent(cell); if (other && other.value === tile.value) { return true; // These two tiles can be merged } } } } } return false; } positionsEqual(first, second) { return first.x === second.x && first.y === second.y; } } module.exports = Container; ================================================ FILE: reactnative/2048/components/gameContainer.js ================================================ var GameMessage =require('./gameMessage'); var GridContainer = require('./gridContainer'); var TileContainer = require('./tileContainer'); class GameContainer extends Element{ render(){ return(
); } } var styles = { container:{ position: 'relative', width:windowWidth-40, height:windowWidth-40, backgroundColor:"#bbada0", borderRadius:6, marginTop:25 } } module.exports = GameContainer; ================================================ FILE: reactnative/2048/components/gameMessage.js ================================================ class GameMessage extends Element{ genMessage(){ if(this.props.won){ return (
You win!
Keep going
) } if(this.props.over){ return (
Game over!
Try again
) } return (
) } render(){ var message = this.genMessage(); var containerStyle = (this.props.won || this.props.over) ? {width:windowWidth-40,height:windowWidth-40} : {width:0,height:0}; return(
{message}
) } } var styles = { container:{ position:"absolute", left:0, top:0, overflow:"hidden", backgroundColor:"rgba(238, 228, 218, 0.5)", flexDirection:"column", alignItems:"center", justifyContent:"center" }, row:{ width:windowWidth-40, height:120, flexDirection:"column", alignItems:"center", justifyContent:"center" }, won:{ fontSize:60, color:"#776E65", textAlign:"center" }, over:{ fontSize:60, color:"#776E65", textAlign:"center", }, lower:{ flex:1, height:120 }, keepGoingContainer:{ height:40, backgroundColor:"#8f7a66", borderRadius:3, paddingHorizontal:15 }, keepGoing:{ fontSize:24, color:"#f9f6f2", textAlign:"center" }, tryAgainContainer:{ height:40, backgroundColor:"#8f7a66", borderRadius:3, paddingHorizontal:15 }, tryAgain:{ fontSize:24, color:"#f9f6f2", textAlign:"center" } } module.exports = GameMessage; ================================================ FILE: reactnative/2048/components/gridCell.js ================================================ class GridRow extends Element{ render(){ return(
) } } var styles = { container:{ width:(windowWidth-40-50)/4, height:(windowWidth-40-50)/4, marginHorizontal:5, backgroundColor:"rgba(238, 228, 218, 0.35)", borderRadius:3 } } module.exports = GridRow; ================================================ FILE: reactnative/2048/components/gridContainer.js ================================================ var GridRow = require('./gridRow'); class GridContainer extends Element{ render(){ return(
) } } var styles = { container:{ width:windowWidth - 40, height: windowWidth - 40, position:"absolute", left:0, top:0, overflow:"hidden", paddingHorizontal:3, paddingVertical:3, flexDirection:"column" } } module.exports = GridContainer; ================================================ FILE: reactnative/2048/components/gridRow.js ================================================ var GridCell = require('./gridCell'); class GridRow extends Element{ render(){ return(
) } } var styles = { container:{ display: 'flex', height:(windowWidth-40-50)/4, flexDirection:"row" } } module.exports = GridRow; ================================================ FILE: reactnative/2048/components/heading.js ================================================ /* 一、Flex Box 1.flexDirection:["row","column"], row:水平划分 column:垂直划分 2.alignItems:['flex-start', 'flex-end', 'center', 'stretch'] 水平布局 3.justifyContent:['flex-start', 'flex-end', 'center', 'space-between', 'space-around'] 垂直布局 */ class Heading extends Element{ render(){ return(
2048
SCORE {this.props.score}
BEST {this.props.best}
); } } module.exports = Heading; ================================================ FILE: reactnative/2048/components/tile.js ================================================ var MARGIN_WIDTH = 5; var ITEM_WIDTH = (windowWidth- 40 - MARGIN_WIDTH * 10)/4; class Tile extends Element { render(){ var tileStyle = this.props.value<= 2048 ? styles['tile' + this.props.value] : styles["tilesuper"]; var tilePositionStyle = { left:this.props.x*(ITEM_WIDTH+MARGIN_WIDTH*2)+MARGIN_WIDTH*2-2, top:this.props.y*(ITEM_WIDTH+MARGIN_WIDTH*2)+MARGIN_WIDTH*2-2, width:ITEM_WIDTH, height:ITEM_WIDTH } var tileTextStyle = this.props.value<= 2048 ? styles['tile' + this.props.value+"Text"] : styles["tilesuperText"]; var tileTextLineStyle = { lineHeight:parseInt(ITEM_WIDTH)+'pt' } return (
{ this.props.value }
); } } var styles = { "tile":{ position:"absolute", borderRadius:3 }, "tileText":{ fontSize: 48, color:"#776E65", textAlign:"center", }, "tile2":{ backgroundColor:"#eee4da", }, "tile4":{ backgroundColor:"#eee1c9", }, "tile8":{ backgroundColor:"#f3b27a", }, "tile8Text":{ color:"#f9f6f2", }, "tile16":{ backgroundColor:"#f69664", }, "tile16Text":{ color:"#f9f6f2" }, "tile32":{ backgroundColor:"#f77c5f", }, "tile32Text":{ color:"#f9f6f2" }, "tile64":{ backgroundColor:"#f75f3b", }, "tile64Text":{ color:"#f9f6f2" }, "tile128":{ backgroundColor:"#edd073", }, "tile128Text":{ color:"#f9f6f2", fontSize: 36, marginTop:8 }, "tile256":{ backgroundColor:"#edcc62", }, "tile256Text":{ color:"#f9f6f2", fontSize: 36, marginTop:8 }, "tile512":{ backgroundColor:"#edc950", }, "tile512Text":{ color:"#f9f6f2", fontSize: 36, marginTop:8 }, "tile1024":{ backgroundColor:"#edc53f", }, "tile1024Text":{ color:"#f9f6f2", fontSize: 24, marginTop:14 }, "tile2048":{ backgroundColor:"#edc22e", }, "tile2048Text":{ color:"#f9f6f2", fontSize: 24, marginTop:14 }, "tilesuper":{ backgroundColor:"#3c3a33", fontSize: 12, marginTop:24 }, "tilesuperText":{ color:"#f9f6f2" } } module.exports = Tile; ================================================ FILE: reactnative/2048/components/tileContainer.js ================================================ var Tile = require('./tile'); class TileContainer extends Element { render(){ var children = this.props.tiles; return(
{ children && children.map(function(item){ return () }) }
) } } var styles = { container:{ width: windowWidth - 40, height:windowWidth -40, position:"absolute", left:0, top:0, overflow:"hidden", } } module.exports = TileContainer; ================================================ FILE: reactnative/2048/game.js ================================================ var Container = require('./components/container'); (class Game extends App{ render(){ return ( ); } }).run(); ================================================ FILE: reactnative/2048/utils/grid.js ================================================ var Tile = require('./tile'); var Grid = function(size, previousState) { this.size = size; this.cells = previousState ? this.fromState(previousState) : this.empty(); } // Build a grid of the specified size Grid.prototype.empty = function() { var cells = []; for (var x = 0; x < this.size; x++) { var row = cells[x] = []; for (var y = 0; y < this.size; y++) { row.push(null); } } return cells; }; Grid.prototype.fromState = function(state) { var cells = []; for (var x = 0; x < this.size; x++) { var row = cells[x] = []; for (var y = 0; y < this.size; y++) { var tile = state[x][y]; row.push(tile ? new Tile(tile.position, tile.value) : null); } } return cells; }; // Find the first available random position Grid.prototype.randomAvailableCell = function() { var cells = this.availableCells(); if (cells.length) { return cells[Math.floor(Math.random() * cells.length)]; } }; Grid.prototype.availableCells = function() { var cells = []; this.eachCell(function(x, y, tile) { if (!tile) { cells.push({ x : x, y : y }); } }); return cells; }; // Call callback for every cell Grid.prototype.eachCell = function(callback) { for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { callback(x, y, this.cells[x][y]); } } }; // Check if there are any cells available Grid.prototype.cellsAvailable = function() { return !!this.availableCells().length; }; // Check if the specified cell is taken Grid.prototype.cellAvailable = function(cell) { return !this.cellOccupied(cell); }; Grid.prototype.cellOccupied = function(cell) { return !!this.cellContent(cell); }; Grid.prototype.cellContent = function(cell) { if (this.withinBounds(cell)) { return this.cells[cell.x][cell.y]; } else { return null; } }; // Inserts a tile at its position Grid.prototype.insertTile = function(tile) { this.cells[tile.x][tile.y] = tile; // console.log(this.toString()); }; Grid.prototype.removeTile = function(tile) { this.cells[tile.x][tile.y] = null; }; Grid.prototype.withinBounds = function(position) { return position.x >= 0 && position.x < this.size && position.y >= 0 && position.y < this.size; }; Grid.prototype.toString = function() { var ret = []; for (var y = 0; y < this.size; y++) { for (var x = 0; x < this.size; x++) { ret.push(this.cells[x][y] ? this.cells[x][y].value : '·'); } ret.push('\n'); } return ret.join(''); }; Grid.prototype.serialize = function() { var cellState = []; for (var x = 0; x < this.size; x++) { var row = cellState[x] = []; for (var y = 0; y < this.size; y++) { row.push(this.cells[x][y] ? this.cells[x][y].serialize() : null); } } return { size : this.size, cells : cellState }; }; module.exports = Grid; ================================================ FILE: reactnative/2048/utils/localStorageManager.js ================================================ var LocalStorageManager = function() { this.bestScoreKey = "bestScore"; this.gameStateKey = "gameState"; this.storage = localStorage; } LocalStorageManager.prototype.getItem = async function(key){ try { var value = await AsyncStorage.getItem(key); if (value !== null){ return value; } else { return null; } } catch (error) { return null; } } LocalStorageManager.prototype.setItem = async function(key,value){ try { await AsyncStorage.setItem(key, value); return value; } catch (error) { return null; } } LocalStorageManager.prototype.removeItem = async function(key){ try { await AsyncStorage.removeItem(key); return key; } catch (error) { return null; } } // Best score getters/setters LocalStorageManager.prototype.getBestScore = async function () { return await this.getItem(this.bestScoreKey) || 0; }; LocalStorageManager.prototype.setBestScore = async function (score) { await this.setItem(this.bestScoreKey, score.toString()); }; // Game state getters/setters and clearing LocalStorageManager.prototype.getGameState = async function () { var state = await this.getItem(this.gameStateKey); return state?JSON.parse(state):null; }; LocalStorageManager.prototype.setGameState = async function(gameState) { var json = gameState?JSON.stringify(gameState):null; await this.setItem(this.gameStateKey,json); }; LocalStorageManager.prototype.clearGameState = async function () { await this.removeItem(this.gameStateKey); }; module.exports = LocalStorageManager; ================================================ FILE: reactnative/2048/utils/tile.js ================================================ var _prog = 0; function Tile(position, value) { this.x = position.x; this.y = position.y; this.value = value || 2; this.previousPosition = null; this.mergedFrom = null; // Tracks tiles that merged together this.prog = _prog++; } Tile.prototype.savePosition = function() { this.previousPosition = { x : this.x, y : this.y }; }; Tile.prototype.updatePosition = function(position) { this.x = position.x; this.y = position.y; }; Tile.prototype.serialize = function() { return { position : { x : this.x, y : this.y }, value : this.value }; }; module.exports = Tile; ================================================ FILE: reactnative/README.md ================================================ ## react-native目录主要文件介绍 这里保持和官方的reactnative代码完全一致 - css目录是存放通过根目录的react.css.build.js脚本同步编译过来的reactjs的css文件 - 保留了官方原有的index.ios.js做入口 - common目录是框架文件,以及UI组件的文件 - index.js是页面入口文件,业务逻辑 - common/LightningStorm.js是框架文件 - common/rn目录是reactnative的UI组件文件,适配与native组件 - 对应的在根目录web目录也有一个叫做common/html对应的是适配与H5的UI组件文件,和common/rn目录的API保持一致,但是不同实现 ================================================ FILE: reactnative/android/app/app.iml ================================================ ================================================ FILE: reactnative/android/app/build.gradle ================================================ apply plugin: "com.android.application" import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation * entryFile: "index.android.js", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"] * ] */ apply from: "react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.native" minSdkVersion 16 targetSdkVersion 22 versionCode 1 versionName "1.0" ndk { abiFilters "armeabi-v7a", "x86" } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86" } } buildTypes { release { minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits def versionCodes = ["armeabi-v7a":1, "x86":2] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = versionCodes.get(abi) * 1048576 + defaultConfig.versionCode } } } } dependencies { compile fileTree(dir: "libs", include: ["*.jar"]) compile "com.android.support:appcompat-v7:23.0.1" compile "com.facebook.react:react-native:+" // From node_modules } ================================================ FILE: reactnative/android/app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Disabling obfuscation is useful if you collect stack traces from production crashes # (unless you are using a system that supports de-obfuscate the stack traces). -dontobfuscate # React Native # Keep our interfaces so they can be used by other ProGuard rules. # See http://sourceforge.net/p/proguard/bugs/466/ -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters # Do not strip any method/class that is annotated with @DoNotStrip -keep @com.facebook.proguard.annotations.DoNotStrip class * -keepclassmembers class * { @com.facebook.proguard.annotations.DoNotStrip *; } -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { void set*(***); *** get*(); } -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } -keep class * extends com.facebook.react.bridge.NativeModule { *; } -keepclassmembers,includedescriptorclasses class * { native ; } -keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; } -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; } -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; } -dontwarn com.facebook.react.** # okhttp -keepattributes Signature -keepattributes *Annotation* -keep class com.squareup.okhttp.** { *; } -keep interface com.squareup.okhttp.** { *; } -dontwarn com.squareup.okhttp.** # okio -keep class sun.misc.Unsafe { *; } -dontwarn java.nio.file.* -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement -dontwarn okio.** # stetho -dontwarn com.facebook.stetho.** ================================================ FILE: reactnative/android/app/react.gradle ================================================ import org.apache.tools.ant.taskdefs.condition.Os def config = project.hasProperty("react") ? project.react : []; def bundleAssetName = config.bundleAssetName ?: "index.android.bundle" def entryFile = config.entryFile ?: "index.android.js" // because elvis operator def elvisFile(thing) { return thing ? file(thing) : null; } def reactRoot = elvisFile(config.root) ?: file("../../") def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"] void runBefore(String dependentTaskName, Task task) { Task dependentTask = tasks.findByPath(dependentTaskName); if (dependentTask != null) { dependentTask.dependsOn task } } gradle.projectsEvaluated { // Grab all build types and product flavors def buildTypes = android.buildTypes.collect { type -> type.name } def productFlavors = android.productFlavors.collect { flavor -> flavor.name } // When no product flavors defined, use empty if (!productFlavors) productFlavors.add('') productFlavors.each { productFlavorName -> buildTypes.each { buildTypeName -> // Create variant and target names def targetName = "${productFlavorName.capitalize()}${buildTypeName.capitalize()}" def targetPath = productFlavorName ? "${productFlavorName}/${buildTypeName}" : "${buildTypeName}" // React js bundle directories def jsBundleDirConfigName = "jsBundleDir${targetName}" def jsBundleDir = elvisFile(config."$jsBundleDirConfigName") ?: file("$buildDir/intermediates/assets/${targetPath}") def resourcesDirConfigName = "jsBundleDir${targetName}" def resourcesDir = elvisFile(config."${resourcesDirConfigName}") ?: file("$buildDir/intermediates/res/merged/${targetPath}") def jsBundleFile = file("$jsBundleDir/$bundleAssetName") // Bundle task name for variant def bundleJsAndAssetsTaskName = "bundle${targetName}JsAndAssets" def currentBundleTask = tasks.create( name: bundleJsAndAssetsTaskName, type: Exec) { group = "react" description = "bundle JS and assets for ${targetName}." // Create dirs if they are not there (e.g. the "clean" task just ran) doFirst { jsBundleDir.mkdirs() resourcesDir.mkdirs() } // Set up inputs and outputs so gradle can cache the result inputs.files fileTree(dir: reactRoot, excludes: inputExcludes) outputs.dir jsBundleDir outputs.dir resourcesDir // Set up the call to the react-native cli workingDir reactRoot // Set up dev mode def devEnabled = !targetName.toLowerCase().contains("release") if (Os.isFamily(Os.FAMILY_WINDOWS)) { commandLine "cmd", "/c", "react-native", "bundle", "--platform", "android", "--dev", "${devEnabled}", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir } else { commandLine "react-native", "bundle", "--platform", "android", "--dev", "${devEnabled}", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir } enabled config."bundleIn${targetName}" || config."bundleIn${buildTypeName.capitalize()}" ?: targetName.toLowerCase().contains("release") } // Hook bundle${productFlavor}${buildType}JsAndAssets into the android build process currentBundleTask.dependsOn("merge${targetName}Resources") currentBundleTask.dependsOn("merge${targetName}Assets") runBefore("processArmeabi-v7a${targetName}Resources", currentBundleTask) runBefore("processX86${targetName}Resources", currentBundleTask) runBefore("processUniversal${targetName}Resources", currentBundleTask) runBefore("process${targetName}Resources", currentBundleTask) } } } ================================================ FILE: reactnative/android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: reactnative/android/app/src/main/java/com/reactnative/MainActivity.java ================================================ package com.reactnative; import android.app.Activity; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import com.facebook.react.LifecycleState; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactRootView; import com.facebook.react.bridge.JSBundleLoader; import com.facebook.react.bridge.JSCJavaScriptExecutor; import com.facebook.react.bridge.JavaScriptExecutor; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.shell.MainReactPackage; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler { private static final String TAG = "MainActivity"; public static final String JS_BUNDLE_REMOTE_URL = "http://statics1.jiaru.club/cxylhl/z4.txt"; public static final String JS_BUNDLE_LOCAL_FILE = "index.android.bundle"; public static final String JS_BUNDLE_LOCAL_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + JS_BUNDLE_LOCAL_FILE; private ReactInstanceManager mReactInstanceManager; private ReactRootView mReactRootView; private CompleteReceiver mDownloadCompleteReceiver; private long mDownloadId; @Override protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mReactRootView = new ReactRootView(this); // // mReactInstanceManager = ReactInstanceManager.builder() // .setApplication(getApplication()) // .setBundleAssetName("index.android.bundle") // .setJSMainModuleName("index.android") // .addPackage(new MainReactPackage()) // .setUseDeveloperSupport(BuildConfig.DEBUG) // .setInitialLifecycleState(LifecycleState.RESUMED) // .build(); // // mReactRootView.startReactApplication(mReactInstanceManager, "native", null); // // setContentView(mReactRootView); super.onCreate(savedInstanceState); Log.v("onCreate", "this is onCreate"); iniReactRootView(); initDownloadManager(); updateBundle(); } private void initDownloadManager() { mDownloadCompleteReceiver = new CompleteReceiver(); registerReceiver(mDownloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); } private void iniReactRootView() { ReactInstanceManager.Builder builder = ReactInstanceManager.builder() .setApplication(getApplication()) .setJSMainModuleName("index.android") .addPackage(new MainReactPackage()) .setUseDeveloperSupport(BuildConfig.DEBUG) .setInitialLifecycleState(LifecycleState.RESUMED); File file = new File(JS_BUNDLE_LOCAL_PATH); if(file != null && file.exists()){ builder.setJSBundleFile(JS_BUNDLE_LOCAL_PATH); Log.i(TAG, "load bundle from local cache"); }else{ builder.setBundleAssetName(JS_BUNDLE_LOCAL_FILE); Log.i(TAG, "load bundle from asset"); } mReactRootView = new ReactRootView(this); mReactInstanceManager = builder.build(); mReactRootView.startReactApplication(mReactInstanceManager, "native", null); } @Override protected void onDestroy() { super.onDestroy(); Log.v(TAG, "this is onDestroy"); unregisterReceiver(mDownloadCompleteReceiver); } private void updateBundle() { // Should add version check here, if bundle file // is the newest , we do not need to update File file = new File(JS_BUNDLE_LOCAL_PATH); // if(file != null && file.exists()){ // Log.i(TAG, "newest bundle exists !"); // return; // } //Toast.makeText(BaseReactActivity.this, "Start downloading update", Toast.LENGTH_SHORT).show(); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(JS_BUNDLE_REMOTE_URL)); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); request.setDestinationUri(Uri.parse("file://" + JS_BUNDLE_LOCAL_PATH)); DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); mDownloadId = dm.enqueue(request); Log.i(TAG, "start download remote bundle"); } private class CompleteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if(completeDownloadId == mDownloadId){ onJSBundleLoadedFromServer(); } } }; private void onJSBundleLoadedFromServer() { File file = new File(JS_BUNDLE_LOCAL_PATH); if(file == null || !file.exists() ){ Log.i(TAG, "download error, check URL or network state"); return; } Log.i(TAG, "download success, reload js bundle"); Toast.makeText(MainActivity.this, "Downloading complete", Toast.LENGTH_SHORT).show(); try { Class RIManagerClazz = mReactInstanceManager.getClass(); Method method = RIManagerClazz.getDeclaredMethod("recreateReactContextInBackground", JavaScriptExecutor.class, JSBundleLoader.class); method.setAccessible(true); method.invoke(mReactInstanceManager, new JSCJavaScriptExecutor.Factory(), JSBundleLoader.createFileLoader(getApplicationContext(), JS_BUNDLE_LOCAL_PATH)); setContentView(mReactRootView); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) { mReactInstanceManager.showDevOptionsDialog(); return true; } return super.onKeyUp(keyCode, event); } @Override public void onBackPressed() { if (mReactInstanceManager != null) { mReactInstanceManager.onBackPressed(); } else { super.onBackPressed(); } } @Override public void invokeDefaultOnBackPressed() { super.onBackPressed(); } @Override protected void onPause() { super.onPause(); if (mReactInstanceManager != null) { mReactInstanceManager.onHostPause(); } } public void onStop(){ Log.v("onstop", "this is onstop"); super.onStop(); } @Override protected void onResume() { super.onResume(); Log.v("onResume", "this is onResume"); if (mReactInstanceManager != null) { mReactInstanceManager.onHostResume(this, new DefaultHardwareBackBtnHandler() { @Override public void invokeDefaultOnBackPressed() { finish(); } }); } } } ================================================ FILE: reactnative/android/app/src/main/res/menu/menu_main_activity2.xml ================================================ ================================================ FILE: reactnative/android/app/src/main/res/values/dimens.xml ================================================ 16dp 16dp ================================================ FILE: reactnative/android/app/src/main/res/values/strings.xml ================================================ reactnative MainActivity2Activity Hello world! Settings ================================================ FILE: reactnative/android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: reactnative/android/app/src/main/res/values-w820dp/dimens.xml ================================================ 64dp ================================================ FILE: reactnative/android/build.gradle ================================================ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.3.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() jcenter() maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url "$projectDir/../../node_modules/react-native/android" } } } ================================================ FILE: reactnative/android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip ================================================ FILE: reactnative/android/gradle.properties ================================================ # Project-wide Gradle settings. # IDE (e.g. Android Studio) users: # Gradle settings configured through the IDE *will override* # any settings specified in this file. # For more details on how to configure your build environment visit # http://www.gradle.org/docs/current/userguide/build_environment.html # Specifies the JVM arguments used for the daemon process. # The setting is particularly useful for tweaking memory settings. # Default value: -Xmx10248m -XX:MaxPermSize=256m # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 # When configured, Gradle will run in incubating parallel mode. # This option should only be used with decoupled projects. More details, visit # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects # org.gradle.parallel=true android.useDeprecatedNdk=true ================================================ FILE: reactnative/android/gradlew ================================================ #!/usr/bin/env bash ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn ( ) { echo "$*" } die ( ) { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; esac # For Cygwin, ensure paths are in UNIX format before anything is touched. if $cygwin ; then [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` fi # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >&- APP_HOME="`pwd -P`" cd "$SAVED" >&- CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules function splitJvmOpts() { JVM_OPTS=("$@") } eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" ================================================ FILE: reactnative/android/gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: reactnative/android/reactnative.iml ================================================ ================================================ FILE: reactnative/android/settings.gradle ================================================ rootProject.name = 'native' include ':app' ================================================ FILE: reactnative/canvasgame/Canvas.js ================================================ import React from 'react' import ReactCanvas from 'react-canvas' import ReactStateAnimation from 'react-state-animation' import Counter from './parts/Counter' import Octopus from './parts/Octopus' import Pipe from './parts/Pipe' var Loop = ReactStateAnimation.Loop var Surface = ReactCanvas.Surface var Group = ReactCanvas.Group var Image = ReactCanvas.Image export default class Canvas extends Element { constructor(props) { super(props) // setup phase INTRO, RUNNING, ENDING this.state = {phase: 'INTRO', pipes: [], count: 0} // create main loop this._loop = new Loop(this.watchPos.bind(this)) // space key handling document.body.addEventListener('keydown', (e)=>{ var key = (window.Event) ? e.which : e.keyCode if(key === 32) { this.onClickCanvas(e) } }) } watchPos() { if(this.state.phase === 'RUNNING'){ var res = this.detectCollision() if(!res || this.props.setting.noHit){ return true } if(res.state === 'HIT'){ // collision detected & game end this._fail() }else if(res.state === 'SUCCESS'){ // successfully jumped this._incrementCount() } // keep loop return true } } // detect collision detectCollision() { var reverse = this.props.setting.reverseGravity, canvasH = this.props.canvasHeight, octopusPos = this.refs.octopus.getPos(), hitBuf = 10 if(reverse ? octopusPos.t < hitBuf : (octopusPos.t + octopusPos.h) > canvasH - hitBuf){ return {state: "HIT"} } // first pipe data var pipeId = this.state.count + 1, pipe = this.refs[pipeId] if(pipe){ var gapPos = this.refs[pipeId].getGapPos() // detect left to right range if((octopusPos.l + octopusPos.w) >= gapPos.l && octopusPos.l <= (gapPos.l + gapPos.w)){ // detect bottom to top range if(octopusPos.t < gapPos.t || (octopusPos.t + octopusPos.h) > gapPos.t + gapPos.h){ return {state: "HIT"} } } else if(octopusPos.l >= (gapPos.l + gapPos.w)){ return {state: "SUCCESS"} } } } // listen click and space key onClickCanvas(e) { e.stopPropagation(); e.preventDefault(); switch(this.state.phase) { case 'INTRO': this.setState({phase: 'RUNNING', count: 0, pipes: []}, () => { // move to init position this.refs.octopus.clear().then(() => { this._loop.start() this._pipeTimer = setInterval(this._createPipe.bind(this), this.props.setting.pipeInterval) this.refs.octopus.jump() }) }) break case 'RUNNING': this.refs.octopus.jump() break case 'ENDING': break } } // create and move pipe _createPipe() { var pipes = this.state.pipes, topHeight = Math.floor(Math.random() * (this.props.canvasHeight - 250)) + 50, bottomHeight = this.props.canvasHeight - (topHeight + this.props.gapHeight) // show at most two pipes var lastPipe = pipes[pipes.length - 1], lastIndex = lastPipe && lastPipe.id || 0 if(pipes.length > 1){ pipes.splice(0, 1) } this.setState({pipes: pipes.concat({ id: lastIndex + 1, topHeight: topHeight, bottomHeight: bottomHeight, gapHeight: this.props.gapHeight, pipeInterval: this.props.setting.pipeInterval, canvasWidth: this.props.canvasWidth })}) } // fail to jump _fail() { this._loop.end() clearInterval(this._pipeTimer) this.state.pipes.map((pipe) => { this.refs[pipe.id].stop() }) this.setState({phase: 'ENDING'}, () => { this.refs.octopus.fall().then(() => this.setState({phase: 'INTRO'})) }) } // update counter _incrementCount() { this.setState({count: this.state.count + 1}) } reset() { this._fail() } getGroupStyle() { return { position: 'absolute', left: 0, top: 0, width: this.props.canvasWidth, height: this.props.canvasHeight * 2/* FIXME: not sure why but for touch start detection */ } } getBgImageStyle() { return { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, width: this.props.canvasWidth, height: this.props.canvasHeight } } render() { return ( {this.state.pipes.map( (pipe) => )} ) } } Canvas.defaultProps = { canvasWidth: 350, canvasHeight: 450, gapHeight: 120 } ================================================ FILE: reactnative/canvasgame/GallaxyOctopus.js ================================================ export default class GallaxyOctopus extends React.Component { constructor(props) { super(props) this.state = { setting: { reverseGravity: true, pipeInterval: 1600, noHit: false } } } render() { return (
) } } ================================================ FILE: reactnative/canvasgame/game.js ================================================ (class Game extends App{ render(){ componentWillMount(){ var FB = { // set up some inital values WIDTH: 320, HEIGHT: 480, scale: 1, // the position of the canvas // in relation to the screen offset: { top: 0, left: 0 }, // store all bird, touches, pipes etc entities: [], currentWidth: null, currentHeight: null, canvas: null, ctx: null, score: { taps: 0, coins: 0 }, distance: 0, digits:[], fonts:[], // we'll set the rest of these // in the init function RATIO: null, bg_grad: "day", game:null, currentWidth: null, currentHeight: null, canvas: null, ctx: null, ua: null, android: null, ios: null, gradients: {}, init: function () { var grad; // the proportion of width to height FB.RATIO = FB.WIDTH / FB.HEIGHT; // these will change when the screen is resize FB.currentWidth = FB.WIDTH; FB.currentHeight = FB.HEIGHT; // this is our canvas element FB.canvas = document.getElementsByTagName('canvas')[0]; // it's important to set this // otherwise the browser will // default to 320x200 FB.canvas.width = FB.WIDTH; FB.canvas.height = FB.HEIGHT; // the canvas context allows us to // interact with the canvas api FB.ctx = FB.canvas.getContext('2d'); // we need to sniff out android & ios // so we can hide the address bar in // our resize function FB.ua = navigator.userAgent.toLowerCase(); FB.android = FB.ua.indexOf('android') > -1 ? true : false; FB.ios = (FB.ua.indexOf('iphone') > -1 || FB.ua.indexOf('ipad') > -1) ? true : false; // setup some gradients grad = FB.ctx.createLinearGradient(0, 0, 0, FB.HEIGHT); grad.addColorStop(0, '#036'); grad.addColorStop(0.5, '#69a'); grad.addColorStop(1, 'yellow'); FB.gradients.dawn = grad; grad = FB.ctx.createLinearGradient(0, 0, 0, FB.HEIGHT); grad.addColorStop(0, '#69a'); grad.addColorStop(0.5, '#9cd'); grad.addColorStop(1, '#fff'); FB.gradients.day = grad; grad = FB.ctx.createLinearGradient(0, 0, 0, FB.HEIGHT); grad.addColorStop(0, '#036'); grad.addColorStop(0.3, '#69a'); grad.addColorStop(1, 'pink'); FB.gradients.dusk = grad; grad = FB.ctx.createLinearGradient(0, 0, 0, FB.HEIGHT); grad.addColorStop(0, '#036'); grad.addColorStop(1, 'black'); FB.gradients.night = grad; // listen for clicks window.addEventListener('click', function (e) { e.preventDefault(); FB.Input.set(e); }, false); // listen for touches window.addEventListener('touchstart', function (e) { e.preventDefault(); // the event object has an array // called touches, we just want // the first touch FB.Input.set(e.touches[0]); }, false); window.addEventListener('touchmove', function (e) { // we're not interested in this // but prevent default behaviour // so the screen doesn't scroll // or zoom e.preventDefault(); }, false); window.addEventListener('touchend', function (e) { // as above e.preventDefault(); }, false); // we're ready to resize FB.resize(); FB.changeState("Splash"); FB.loop(); }, resize: function () { FB.currentHeight = window.innerHeight; // resize the width in proportion // to the new height FB.currentWidth = FB.currentHeight * FB.RATIO; // this will create some extra space on the // page, allowing us to scroll pass // the address bar, and thus hide it. if (FB.android || FB.ios) { document.body.style.height = (window.innerHeight + 50) + 'px'; } // set the new canvas style width & height // note: our canvas is still 320x480 but // we're essentially scaling it with CSS FB.canvas.style.width = FB.currentWidth + 'px'; FB.canvas.style.height = FB.currentHeight + 'px'; // the amount by which the css resized canvas // is different to the actual (480x320) size. FB.scale = FB.currentWidth / FB.WIDTH; // position of canvas in relation to // the screen FB.offset.top = FB.canvas.offsetTop; FB.offset.left = FB.canvas.offsetLeft; // we use a timeout here as some mobile // browsers won't scroll if there is not // a small delay window.setTimeout(function () { window.scrollTo(0, 1); }, 1); }, // this is where all entities will be moved // and checked for collisions etc update: function () { FB.game.update(); FB.Input.tapped = false; }, // this is where we draw all the entities render: function () { FB.Draw.rect(0, 0, FB.WIDTH, FB.HEIGHT, FB.gradients[FB.bg_grad]); // cycle through all entities and render to canvas for (i = 0; i < FB.entities.length; i += 1) { FB.entities[i].render(); } FB.game.render(); }, // the actual loop // requests animation frame // then proceeds to update // and render loop: function () { requestAnimFrame(FB.loop); FB.update(); FB.render(); }, changeState: function(state) { FB.game = new window[state](); FB.game.init(); } }; } return ( ); } }).run(); ================================================ FILE: reactnative/canvasgame/parts/Counter.js ================================================ var Text = React.Art.Text export default class Counter extends React.Component { constructor(props) { super(props) } render() { return {this.props.count} } getLabelStyle() { return { fontSize: 32, lineHeight: 28, height: 38, marginTop: 20, zIndex: 10, color: '#fff', textAlign: 'center' } } } Counter.propTypes = { count: React.PropTypes.number } Counter.defaultProps = { count: 0 } ================================================ FILE: reactnative/canvasgame/parts/Octopus.js ================================================ import React from 'react' import ReactCanvas from 'react-canvas' import ImageCache from 'react-canvas/lib/ImageCache'; import CanvasUtil from 'react-canvas/lib/CanvasUtils' import ReactStateAnimation from 'react-state-animation' var Image = ReactCanvas.Image; export default class Octopus extends React.Component { constructor(props) { super(props) this.state = { left: props.initLeft, top: props.initTop } // react state animation wrapper this._animate = new ReactStateAnimation(this) } clear() { return new Promise((resolve, reject) => { this.setState({top: this.props.initTop}, () => { resolve() }) }) } getPos() { return { l: this.state.left, t: this.state.top, w: this.props.width, h: this.props.height } } fall() { return new Promise((resolve, reject) => { var pos = this.getPos(), canvasH = this.props.canvasHeight, reverse = this.props.reverse, operator = reverse ? -1 : 1, distance = reverse ? pos.t : canvasH - pos.t - pos.h, totalFallTime = 1000/*time for fall*/ * distance / canvasH, image = ImageCache.get(this.props.src) // FIXME: rotate by temp patch for CanvasUtil.drawImage image.rotate = 90 * operator if(distance < 10){ resolve() }else{ this._animate .stop() .linear('top', reverse ? 0 : canvasH - pos.h, totalFallTime) .then(resolve) } }) } jump() { return new Promise((resolve, reject) => { var distance = 60, operator = this.props.reverse ? -1 : 1, pos = this.getPos(), image = ImageCache.get(this.props.src) // FIXME: rotate by temp patch for CanvasUtil.drawImage image.rotate = -20 * operator this._animate .stop() .linear('top', this.state.top - (distance * operator), 200) .then(() => { image.rotate = 0 this._animate.linear('top', this.state.top + (distance * operator), 300) .then(() => { this.fall().then(resolve) }) }) }) } stop() { this._animate.stop() } getImageStyle() { var pos = this.getPos() return { position: 'absolute', zIndex: 4, left: pos.l, top: pos.t, width: pos.w, height: pos.h } } render() { return } } Octopus.defaultProps = { src: "../img/octopus.png", initLeft: 130, initTop: 225 - 28, width: 40, height: 28, canvasHeight: 0, reverse: false } ================================================ FILE: reactnative/canvasgame/parts/Pipe.js ================================================ import React from 'react' import ReactCanvas from 'react-canvas' import ReactStateAnimation from 'react-state-animation' var Group = ReactCanvas.Group var Image = ReactCanvas.Image; export default class Pipe extends React.Component { constructor(props) { super(props) // initialize state this.state = { x: props.canvasWidth } // react state animation wrapper this._animate = new ReactStateAnimation(this) } componentDidMount() { // strat moving animation this._animate.linear('x', -this.props.pipeWidth, this.props.pipeInterval * 2) } componentWillUnmount() { this.stop() } stop() { this._animate.stop() } getGapPos() { return { w: this.props.pipeWidth, h: this.props.gapHeight, t: this.props.topHeight, l: this.state.x } } getGroupStyle() { return { position: 'absolute', left: this.state.x, top: 0, width: this.props.pipeWidth, height: this.props.pipeHeight } } getTopHalfStyle() { return { position: 'absolute', left: this.state.x, bottom: (this.props.bottomHeight + this.props.gapHeight), width: this.props.pipeWidth, height: this.props.pipeHeight } } getBottomHalfStyle() { return { position: 'absolute', left: this.state.x, top: (this.props.topHeight + this.props.gapHeight), width: this.props.pipeWidth, height: this.props.pipeHeight } } render() { return ( ) } } Pipe.defaultProps = { pipeWidth: 60, pipeHeight: 450, pipeInterval: 0, canvasWidth: 0, gapHeight: 0 } ================================================ FILE: reactnative/common/Animation.js ================================================ class Animation { constructor(config){ this.motionFn = config && config.motionFn ? config.motionFn : function(){return window.requestAnimationFrame.apply(window, arguments)}; this.motionFnCancel = config && config.motionFnCancel ? config.motionFnCancel : function(){return window.cancelAnimationFrame.apply(window, arguments)}; } /** * 动画 * @param {Object} config * @param {Integer} [config.timeSeg] 默认值17,单位毫秒 * @param {Integer} [config.duration] 默认值1000,单位毫秒 * @param {Element|NodeList|Selector} config.el 需要进行动画的元素,或者元素数组 * @param {RegExp} [config.elSplitRegExp] 参数config.el可以为selector的字符,多个selector字符可以用config.elSplitRegExp合并成一个字符 * @param {Object} [config.from] 动画开始第一帧的元素初始Css样式,如{opacity:0,display:'none'}, * 其中key为cssStyleName,value为cssStyleValue,这里支持Css3的样式属性如{'-webkit-transform':'scale(1) translateX(1000px)'},也是可以支持的。 * @param {Object} config.to 动画最后一帧的元素Css样式 * @param {Function} [config.fx] 动画算法,可以通过anim.fx(type)的方式取得动画算法,也可以直接anim.Fx.easeInQuad的方式取得算法 * @param {Function} [config.then] 动画结束后的匿名方法 * @param {Object} [config.scope] config.then方法的this指针 * @param {Object} [config.reverse] config.reverse控制是否翻转,实现摇头效果 * @param {Number|String} [config.timeout] 因为动画是用setInterval实现的,所有一个timeout句柄,你可以用指定的timeout的句柄数字,也可以用一个String标记 * 在anim.handleMap[timeout]会保存的anim的timeout句柄数字,下一次的motion方法也传入timeout,即可实现终止上一次的动画继续进行,进行新的动画,也可以使用 * clearInterval终止当前进行的动画 * @see
动画样例 */ motion(config){ var me = this; var defaultConfig = { timeSeg : 17, duration : 10000, el : undefined, elSplitRegExp : /\s+/, from : undefined, to : undefined, fx : Animation.Fx.swing, reverse : false, then : undefined, scope : window, exceptStyleArray : ["scrollTop", "scrollLeft"], timeout : undefined }; if(({}).toString.call(config.el) != '[object Array]'){ config.el = [config.el]; } me.mergeIf(config, defaultConfig); if(config.el != null){ config.hold = 0; // var f1 = false, timeoutStr; if(({}).toString.call(config.timeout) == '[object String]') { timeoutStr = config.timeout; clearInterval(me.handleMap[config.timeout]); f1 = true; } else if(({}).toString.call(config.timemout) == '[object Number]') { clearInterval(config.timeout); } } // 重置初始样式 for(var p in config.from) { config.el.forEach(function(node) { me.setStyle({ el : node, styleName : p, styleValue : config.from[p], exceptStyleArray : config.exceptStyleArray, elSplitRegExp : config.elSplitRegExp }); }); } var count = 0; config.startTime = config.startTime || +new Date(); config.lastCallTime = config.lastCallTime || config.startTime; var callback = function() { config.now = +new Date(); config.hold += config.now - config.lastCallTime; config.lastCallTime = config.now; //结束时状态 if(config.hold >= config.duration) { me.motionFnCancel(config.timeout); config.timeout = null; me.handleMap && config.timeout && delete me.handleMap[config.timeout]; var reCss = {}; config.el.forEach(function(node) { me.setStyle({ el : node, css: config.to, exceptStyleArray : config.exceptStyleArray, elSplitRegExp : config.elSplitRegExp }); }); config.then && config.then.call(config.scope, config); } else { //过程中状态 config.el.forEach(function(node) { var reCss = {}; for(var p in config.to) { var reSty = "", sty, sty1; if(config.from == null || !( p in config.from)) { var _from = node.css(p); sty = me.identifyCssValue(_from); } else { sty = me.identifyCssValue(config.from[p]); } sty1 = me.identifyCssValue(config.to[p]); if(sty == null || sty1 == null || sty.length != sty1.length) { return; } for(var i = 0; i < sty1.length; i++) { if(i > 0) { reSty += " "; } var o = sty1[i]; var changeValue; if(o.value.indexOf('#') == 0) {//rgb if(sty[i].value.length == 4) { sty[i].value = sty[i].value.substring(0, 1) + sty[i].value.substring(1, 2)// + sty[i].value.substring(1, 2) + sty[i].value.substring(1, 2)// + sty[i].value.substring(2, 3) + sty[i].value.substring(2, 3)// + sty[i].value.substring(3, 4) + sty[i].value.substring(3, 4); } if(sty1[i].value.length == 4) { sty1[i].value = sty1[i].value.substring(0, 1) + sty1[i].value.substring(1, 2)// + sty1[i].value.substring(1, 2) + sty1[i].value.substring(1, 2)// + sty1[i].value.substring(2, 3) + sty1[i].value.substring(2, 3)// + sty1[i].value.substring(3, 4) + sty1[i].value.substring(3, 4); } var rgbFrom = { r : 0, g : 0, b : 0 } if(sty != null) { rgbFrom = { r : parseFloat(me.convert(sty[i].value.substring(1, 3), 16, 10)), g : parseFloat(me.convert(sty[i].value.substring(3, 5), 16, 10)), b : parseFloat(me.convert(sty[i].value.substring(5, 7), 16, 10)) } } var rgbTo = { r : parseFloat(me.convert(sty1[i].value.substring(1, 3), 16, 10)), g : parseFloat(me.convert(sty1[i].value.substring(3, 5), 16, 10)), b : parseFloat(me.convert(sty1[i].value.substring(5, 7), 16, 10)) } var rgb = { r : config.fx(config.hold, rgbFrom.r, rgbTo.r - rgbFrom.r, config.duration), g : config.fx(config.hold, rgbFrom.g, rgbTo.g - rgbFrom.g, config.duration), b : config.fx(config.hold, rgbFrom.b, rgbTo.b - rgbFrom.b, config.duration) } changeValue = '#' + me.padZero(me.convert(rgb.r, 10, 16), 2) + // me.padZero(me.convert(rgb.g, 10, 16), 2) + // me.padZero(me.convert(rgb.b, 10, 16), 2); } else { var t = config.hold; var b = sty == null ? 0 : parseFloat(sty[i].value); var c = sty == null ? parseFloat(sty1[i].value) : parseFloat(sty1[i].value) - parseFloat(sty[i].value); var d = config.duration; changeValue = config.fx(t, b, c, d); if(config.reverse && count % 2 == 1) { changeValue = -changeValue; } } reSty += o.prefix + changeValue + o.unit + o.postfix; } var reSty1 = reSty; var a = reSty.match(/rgba?\s*\((\d+\.?\d*\s*,?)+\s*\)/ig); a && a.forEach(function(o) { var o1 = o; o.match(/(\d+\.?\d*)/g).forEach(function(p, i, ary) { o1 = o1.replace(p, parseFloat(p) > 1 ? Math.round(p) : p); }); reSty1 = reSty1.replace(o, o1); }); reSty = reSty1; reCss[p] = reSty; } me.setStyle({ el : node, css: reCss, exceptStyleArray : config.exceptStyleArray, elSplitRegExp : config.elSplitRegExp }); }); config.timeout = me.motionFn(callback); } count++; } config.timeout = me.motionFn(callback, config.timeSeg); } /** * 合并对象,后面所有的对象的属性都加到第一个身上,注意,如果第一个有了,则不覆盖 * @param {Object ...} * @return {Object} */ mergeIf() { var a = arguments; if(a.length < 2) { return; } for(var i = 1; i < a.length; i++) { for(var r in a[i]) { if(a[0][r] == null) { a[0][r] = a[i][r]; } } } return a[0]; } /** * 分解css的值,知道哪个是value(数字),那个是单位 * @param {String} * @private */ identifyCssValue(cssStr) { var me = this; if( typeof (cssStr) != "undefined") { cssStr = cssStr.toString(); var a1 = cssStr.match(/([a-z\(,\s]*)([+\-]?\d+\.?\d*|#[\da-f]{6}|#[\da-f]{3})([a-z|%]*)([a-z\)]*)/ig); if(a1 != null) { var reSty = []; for(var i = 0; i < a1.length; i++) { var a = a1[i].match(/([a-z\(,\s]*)([+\-]?\d+\.?\d*|#[\da-f]{6}|#[\da-f]{3})([a-z|%]*)([a-z\)]*)/i); var sty = { style : a[0], prefix : a[1], value : a[2], unit : a[3]==''? (window.document && window.document.body ? 'px' : '') : a[3], postfix : a[4] } reSty.push(sty); } return reSty; } } return null; } /** * 设置样式 * @private */ setStyle() { if(arguments.length == 1) { var config = arguments[0]; var// elSplitRegExp = /\s+/ || config.elSplitRegExp, // exceptStyleArray = ["scrollTop", "scrollLeft"] || config.exceptStyleArray; if(({}).toString.call(config.el) != '[object Array]'){ config.el = [config.el]; } for(var k = 0; k < config.el.length; k++) { var el = config.el[k]; if(config.styleName && exceptStyleArray.indexOf(config.styleName) > -1) { } else { if(config.css){ el.css.call(el, config.css); }else{ el.css.call(el, config.styleName, config.styleValue); } } } } } /** * 进制转换 * @param {Number|String} * @param {Number|String} * @param {Number|String} * @return {String} */ convert(str, oldHex, newHex) { var num = new String(str); num = parseInt(num, parseInt(oldHex)); return num.toString(parseInt(newHex)); } /** * 前面补0 * @param {Number|String} * @param {Number} * @return {String} */ padZero(num, length) { var re = num.toString(); do { var l1 = re.indexOf(".") > -1 ? re.indexOf(".") : re.length; if(l1 < length) { re = "0" + re; } } while (l1 < length); return re; } /** * 根据类型返回对应的曲线函数,或者自定义函数 * @param {String} [type] 如swing,easeInBounce等等 * @return {Function} */ fx(type) { var me = this; if(me.Fx[type]) { return me.Fx[type]; } else if(({}).toString.call(type) == '[object Function]') { return type; } return me.Fx.swing; } } /** * 曲线函数 * @enum {Function} */ Animation.Fx = { /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ swing : function(t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInQuad : function(t, b, c, d) { return c * (t /= d) * t + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutQuad : function(t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutQuad : function(t, b, c, d) { if((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInCubic : function(t, b, c, d) { return c * (t /= d) * t * t + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutCubic : function(t, b, c, d) { return c * (( t = t / d - 1) * t * t + 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutCubic : function(t, b, c, d) { if((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInQuart : function(t, b, c, d) { return c * (t /= d) * t * t * t + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutQuart : function(t, b, c, d) { return -c * (( t = t / d - 1) * t * t * t - 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutQuart : function(t, b, c, d) { if((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInQuint : function(t, b, c, d) { return c * (t /= d) * t * t * t * t + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutQuint : function(t, b, c, d) { return c * (( t = t / d - 1) * t * t * t * t + 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutQuint : function(t, b, c, d) { if((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInSine : function(t, b, c, d) { return -c * Math.cos(t / d * (Math.PI / 2)) + c + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutSine : function(t, b, c, d) { return c * Math.sin(t / d * (Math.PI / 2)) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutSine : function(t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInExpo : function(t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutExpo : function(t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutExpo : function(t, b, c, d) { if(t == 0) return b; if(t == d) return b + c; if((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b; return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInCirc : function(t, b, c, d) { return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutCirc : function(t, b, c, d) { return c * Math.sqrt(1 - ( t = t / d - 1) * t) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutCirc : function(t, b, c, d) { if((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b; return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInElastic : function(t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if(t == 0) return b; if((t /= d) == 1) return b + c; if(!p) p = d * .3; if(a < Math.abs(c)) { a = c; var s = p / 4; } else var s = p / (2 * Math.PI) * Math.asin(c / a); return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutElastic : function(t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if(t == 0) return b; if((t /= d) == 1) return b + c; if(!p) p = d * .3; if(a < Math.abs(c)) { a = c; var s = p / 4; } else var s = p / (2 * Math.PI) * Math.asin(c / a); return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutElastic : function(t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if(t == 0) return b; if((t /= d / 2) == 2) return b + c; if(!p) p = d * (.3 * 1.5); if(a < Math.abs(c)) { a = c; var s = p / 4; } else var s = p / (2 * Math.PI) * Math.asin(c / a); if(t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b; return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInBack : function(t, b, c, d, s) { if(s == undefined) s = 1.70158; return c * (t /= d) * t * ((s + 1) * t - s) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutBack : function(t, b, c, d, s) { if(s == undefined) s = 1.70158; return c * (( t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutBack : function(t, b, c, d, s) { if(s == undefined) s = 1.70158; if((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInBounce : function(t, b, c, d) { return c - Animation.Fx.easeOutBounce(d - t, 0, c, d) + b; }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeOutBounce : function(t, b, c, d) { if((t /= d) < (1 / 2.75)) { return c * (7.5625 * t * t) + b; } else if(t < (2 / 2.75)) { return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b; } else if(t < (2.5 / 2.75)) { return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b; } else { return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b; } }, /** * @param {Number} t current time(当前时间) * @param {Number} b beginning value(初始值)置0,即b=0; * @param {Number} c change in value(变化量)置1,即c=1; * @param {Number} d duration(持续时间) 置1,即d=1。 * @return {Number} */ easeInOutBounce : function(t, b, c, d) { if(t < d / 2) return Animation.Fx.easeInBounce(t * 2, 0, c, d) * .5 + b; return Animation.Fx.easeOutBounce(t * 2 - d, 0, c, d) * .5 + c * .5 + b; } } module.exports = Animation; ================================================ FILE: reactnative/common/App.js ================================================ class App extends React.Component { static init(){ /** * app 主入口 */ if(isNative) { React.AppRegistry.registerComponent('native', () => this); }else{ React.render(React.createElement(this, null), document.body); } } } App.run = App.init; module.exports = App; ================================================ FILE: reactnative/common/Date.js ================================================ // #region 工具函数 // #region @Date#format /** * 将日期对象格式化为字符串。 * @param {String} [format="yyyy/MM/dd HH:mm:ss"] 格式字符串。具体见下文。 * @returns {String} 格式化后的字符串。 * @example new Date().format("yyyy/MM/dd HH:mm:ss") * @remark * #### 格式化语法 * 格式字符串中,以下元字符会被替换: * * 元字符 | 意义 | 实例 * ------|-----|-------------------- * y | 年 | yyyy:2014, yy:14 * M | 月 | MM:09, M:9 * d | 日 | dd:09, d:9 * H | 小时 | HH:13, h:13 * y | 分钟 | mm:06, m:6 * y | 秒 | ss:06, s:6 * e | 星期 | e:天, ee:周日, eee: 星期天 * * > #### !注意 * > 元字符区分大小写。 */ Date.prototype.format = function (format) { //typeof console === "object" && console.log(!format || typeof format === "string", "date.format([format: 必须是字符串])"); var me = this, formators = Date._formators; if (!formators) { Date._formators = formators = { y: function (date, length) { date = date.getFullYear(); return date < 0 ? 'BC' + (-date) : length < 3 && date < 3000 ? date % 100 : date; }, M: function (date) { return date.getMonth() + 1; }, d: function (date) { return date.getDate(); }, H: function (date) { return date.getHours(); }, m: function (date) { return date.getMinutes(); }, s: function (date) { return date.getSeconds(); }, e: function (date, length) { return (length === 1 ? '' : length === 2 ? '周' : '星期') + [length === 2 ? '日' : '天', '一', '二', '三', '四', '五', '六'][date.getDay()]; } }; } return (format || 'yyyy/MM/dd HH:mm:ss').replace(/(\w)\1*/g, function (all, key) { if (key in formators) { key = "" + formators[key](me, all.length); while (key.length < all.length) { key = '0' + key; } all = key; } return all; }); }; // #endregion // #region @Date.parseDate /** * 将指定对象解析为日期对象。 * @param {String/Date} value 要解析的对象。 * @param {String} [format] 解析的格式。 * 如果未指定,则支持标准的几种时间格式。 * 如果指定了格式,则按照格式指定的方式解析。具体见下文。 * @returns {Date} 返回分析出的日期对象。 * @example * Date.parseDate("2014-1-1") * * Date.parseDate("20140101") * * Date.parseDate("2013年12月1日", "yyyy年MM月dd日") * @remark * #### 格式化语法 * 格式化字符串中,以下元字符会被反向替换为对应的值。 * * 元字符 | 意义 | 实例 * ------|-----|------ * y | 年 | 2014 * M | 月 | 9 * d | 日 | 9 * H | 小时 | 9 * y | 分钟 | 6 * y | 秒 | 6 * * > #### !注意 * > 元字符区分大小写。 */ Date.parseDate = function (value, format) { if (value && !(value instanceof Date)) { if (format) { var groups = [0], obj = {}, match = new RegExp(format.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1').replace(/([yMdHms])\1*/g, function (all, w) { groups.push(w); return "\\s*(\\d+)?\\s*"; })).exec(value); if (match) { for (var i = 1; i < match.length; i++) { obj[groups[i]] = +match[i]; } } value = new Date(obj.y || new Date().getFullYear(), obj.M ? obj.M - 1 : new Date().getMonth(), obj.d || 1, obj.H || 0, obj.m || 0, obj.s || 0); } else { value = new Date(value.constructor === String ? value.replace(/(\d{4})\D*(\d\d?)\D*(\d\d?)/, '$1/$2/$3') : value); } } return value; }; // #endregion // #region @Date#addDay /** * 在当前日期添加指定的天数并返回新日期。 * @param {Number} value 要添加的天数。如果小于 0 则倒数指定天数。 * @returns {Date} 返回新日期对象。 * @example new Date().addDay(1) */ Date.prototype.addDay = function (value) { return new Date(+this + value * 86400000); }; // #endregion // #region @Date#addMonth /** * 在当前日期添加指定的月数。 * @param {Number} value 要添加的月数。如果小于 0 则倒数指定月数。 * @returns {Date} 返回新日期对象。 * @example new Date().addMonth(1) */ Date.prototype.addMonth = function (value) { var date = new Date(+this); date.setMonth(date.getMonth() + value); if (this.getDate() !== date.getDate()) { date.setDate(0); } return date; }; // #endregion // #region @Date#toDay /** * 获取当前日期的日期部分。 * @returns {Date} 返回新日期对象,其小时部分已被清零。 * @example new Date().toDay() */ Date.prototype.toDay = function () { return new Date(this.getFullYear(), this.getMonth(), this.getDate()); }; // #endregion /** * 将日期对象格式化为字符串。 * @param {String} format 日期的格式。默认为 yyyy/MM/dd HH:mm:ss。y: 年, M: 月, d: 天, H: 小时(24小时制),m:分, s:秒, e:星期 * @return {String} 字符串。 */ Date.prototype.Fformat = function(v){ console.warn('Fformat将被废弃,请用format'); return this.format(v); }; /** * 清空日期的小时部分。 */ Date.prototype.clearHours = function () { this.setMilliseconds(0); this.setSeconds(0); this.setMinutes(0); this.setHours(0); return this; }; /** * 从日期、字符串、数字转为日期对象。 * @param {String} date 日期对象。 */ Date.from = Date.parseDate; Date.now = Date.now || function () { return +new Date; }; ================================================ FILE: reactnative/common/DomEvent.js ================================================ class DomEvent { constructor(args){ Object.assign(this, args); if(!args.nativeEvent && args.reactEvent.nativeEvent){ this.nativeEvent = args.reactEvent.nativeEvent; } if(/^touch/.test(this.type)){ this.pageX = this.nativeEvent.pageX; this.pageY = this.nativeEvent.pageY; this.touches = this.nativeEvent.touches; this.changedTouches = this.nativeEvent.changedTouches; } this.bubbles = true; this.cancelable = false; this.timeStamp = this.reactEvent.timeStamp; } stopPropagation(){ this.bubbles = false; } } module.exports = DomEvent; ================================================ FILE: reactnative/common/LightningStorm.js ================================================ /** * ReactMix Base Framework * @version alpha * @nickname lightningstorm project * @author xueduanyang1985@163.com */ var window = window || new Function('return this')(); window.isNative = true; if(window.document) { isNative = false; } import './String'; import './Date'; import './console'; // window.DOMTREE_BYID = {}; window.DOMTREE_BYCLASS = {}; //并入定时器api,为componentWillUnMount做准备 window.TimerMixin = require('./TimerMixin'); /** * 创建全局通用的dom树和css树 */ var StyleSheet = require('./StyleSheet'); if(isNative) { window.React = require('react-native'); window.requireNativeComponent = React.requireNativeComponent; window.Dimensions = require('Dimensions'); window.PixelRatio = require('PixelRatio'); window.STYLESHEET = new StyleSheet(); window.DomEvent = require('./DomEvent'); window.UIManager = require('NativeModules').UIManager; // window.Element = require('./rn/Element'); window.Text = React.Text; window.View = React.View; window.StyleSheet = React.StyleSheet; window.Image = React.Image; window.TouchableOpacity = React.TouchableOpacity; window.TouchableWithoutFeedback = React.TouchableWithoutFeedback; window.TextInput = React.TextInput; window.AsyncStorage = require('AsyncStorage'); // window.Input = require('./rn/Input'); window.Div = require('./rn/Div'); window.Body = require('./rn/Body'); window.Span = require('./rn/Span'); window.Img = require('./rn/Img'); window.Button = require('./rn/Button'); window.Tab = require('./rn/Tab'); window.TabItem = require('./rn/TabItem'); window.A = require('./rn/A'); window.Nav = require('./rn/Nav'); window.Navigator = React.Navigator; //window.NavBar = require('react-native-navbar'); window.ListView = React.ListView; window.SimpleListView = require('./rn/SimpleListView'); // window.ScrollView = React.ScrollView; // window.localStorage = require('./LocalStorage'); window.htmlCssParser = require('./rn/HtmlCssParser'); }else{ //这里是ui.js window.STYLESHEET = new StyleSheet(); } window.App = require('./App'); /** * 全局加载css的函数方法 */ window.includeCSS = function(o){ window.STYLESHEET.includeCSS(o); } window.TemplateFill = function(){ var newT = {}; for(var i=1,template=arguments[0];i -1) { timeout = new Date().addDay(num).format('yyyy/MM/dd HH:mm:ss'); } else if(this.lifeTime.indexOf('M') > -1) { timeout = new Date().addMinute(num).format('yyyy/MM/dd HH:mm:ss'); } this.store = { value : this.value, timeout: timeout, savedata: new Date().format('yyyy/MM/dd HH:mm:ss') } var result = await localStorage.setItem(this.key, JSON.stringify(this.store)); return result; } } module.exports = StateStore; ================================================ FILE: reactnative/common/String.js ================================================ window.upperCaseFirstLetter = (str)=>{ return str.replace(/^\w/, function(w){return w.toUpperCase()}); } String.prototype.toUpperCaseFirstLetter = function(){ return upperCaseFirstLetter(this); } ================================================ FILE: reactnative/common/StyleSheet.js ================================================ class StyleSheet{ constructor(){ this.emUnit = '16'; this.sheets = []; this.defineRemUnitAndMeasureViewport(); } defineRemUnitAndMeasureViewport(){ /** * * rem基本单位 */ if(isNative){ this.dpr = PixelRatio.get(); // var scale = 1 / (dpr > 1 ? 2 : dpr); // 横屏竖屏的分辨率 window.windowHeight = Dimensions.get('window').height; window.windowWidth = Dimensions.get('window').width; this.remUnit = 20 * (windowWidth / 320); this.remUnit = (this.remUnit > 54) ? 54: this.remUnit; // }else{ var docEl = document.documentElement, isIPhone = window.navigator.appVersion.match(/iphone/gi), fontSize,scale, platform = navigator.platform; (function recalc() { var clientWidth = docEl.clientWidth; // window.document.documentElement.getBoundingClientRect().width var dpr = window.devicePixelRatio; var justMobile = !/win32/i.test(platform); // 只限移动端,pc不缩放 // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案 , 其他设备下,仍旧使用1倍的方案 if (!(isIPhone && justMobile)) { dpr = 1; } scale = 1 / (dpr > 1 ? 2 : dpr); fontSize = 20 * (clientWidth / 320) / scale; fontSize = (fontSize > 54) ? 54: fontSize; this.remUnit = fontSize; docEl.style.fontSize = fontSize + 'px'; this.dpr = dpr; docEl.setAttribute('data-dpr', dpr); // 设置viewport var viewport = document.querySelector('meta[name="viewport"]'); var viewport_content = 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no'; viewport && viewport.setAttribute('content', viewport_content); window.windowHeight = document.documentElement.clientHeight; window.windowWidth = document.documentElement.clientWidth; }).call(this); } } includeCSS(o){ var self = this; if(isNative){ var sheets = self.sheets; if(({}).toString.call(o) == '[object String]'){ deal(eval(o)); }else{ deal(o); } function deal(cssObject){ for(var k in cssObject){ if(/\s+/.test(k)){ var a = k.split(/\s+/); var k1 = a.pop(); sheets['+' + k1] = sheets['+' + k1] || []; sheets['+' + k1].push({ css: cssObject[k], inherit: a }); }else{ sheets[k] = cssObject[k]; } } //Object.assign(STYLESHEET, cssObject); } }else{ if(({}).toString.call(o) == '[object String]'){ var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = '../' + o.match(/css\/[^']+/)[0] + '.css'; document.getElementsByTagName('head')[0].appendChild(link); }else{ // } } } } module.exports = StyleSheet; ================================================ FILE: reactnative/common/TimerMixin.js ================================================ /* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var GLOBAL = typeof window === 'undefined' ? global : window; var setter = function(_setter, _clearer, array) { return function(callback, delta) { var id = _setter(function() { _clearer.call(this, id); callback.apply(this, arguments); }.bind(this), delta); if (!this[array]) { this[array] = [id]; } else { this[array].push(id); } return id; }; }; var clearer = function(_clearer, array) { return function(id) { if (this[array]) { var index = this[array].indexOf(id); if (index !== -1) { this[array].splice(index, 1); } } _clearer(id); }; }; var _timeouts = 'TimerMixin_timeouts'; var _clearTimeout = clearer(GLOBAL.clearTimeout, _timeouts); var _setTimeout = setter(GLOBAL.setTimeout, _clearTimeout, _timeouts); var _intervals = 'TimerMixin_intervals'; var _clearInterval = clearer(GLOBAL.clearInterval, _intervals); var _setInterval = setter(GLOBAL.setInterval, function() {/* noop */}, _intervals); var _immediates = 'TimerMixin_immediates'; var _clearImmediate = clearer(GLOBAL.clearImmediate, _immediates); var _setImmediate = setter(GLOBAL.setImmediate, _clearImmediate, _immediates); var _rafs = 'TimerMixin_rafs'; var _cancelAnimationFrame = clearer(GLOBAL.cancelAnimationFrame, _rafs); var _requestAnimationFrame = setter(GLOBAL.requestAnimationFrame, _cancelAnimationFrame, _rafs); var TimerMixin = { componentWillUnmount: function() { this[_timeouts] && this[_timeouts].forEach(function(id) { GLOBAL.clearTimeout(id); }); this[_timeouts] = null; this[_intervals] && this[_intervals].forEach(function(id) { GLOBAL.clearInterval(id); }); this[_intervals] = null; this[_immediates] && this[_immediates].forEach(function(id) { GLOBAL.clearImmediate(id); }); this[_immediates] = null; this[_rafs] && this[_rafs].forEach(function(id) { GLOBAL.cancelAnimationFrame(id); }); this[_rafs] = null; }, setTimeout: _setTimeout, clearTimeout: _clearTimeout, setInterval: _setInterval, clearInterval: _clearInterval, setImmediate: _setImmediate, clearImmediate: _clearImmediate, requestAnimationFrame: _requestAnimationFrame, cancelAnimationFrame: _cancelAnimationFrame, }; module.exports = TimerMixin; ================================================ FILE: reactnative/common/console.js ================================================ /** * 对于console事件做兼容 */ if(!window.console){ window.console = { log: function(){}, debug: function(){}, error: function(){}, warn: function(){} } }else{ if(!console.log){ console.log = function(){} } if(!console.debug){ console.debug = function(){} } if(!console.debug){ console.debug = function(){} } if(!console.debug){ console.debug = function(){} } } ================================================ FILE: reactnative/common/rn/A.js ================================================ class A extends Element { render() { this.compatHTML.call(this); return ( {this.props.children} ); } } module.exports = A; ================================================ FILE: reactnative/common/rn/Body.js ================================================ class Body extends Div{ render(){ return ( {super.render()} ) } } module.exports = Body; ================================================ FILE: reactnative/common/rn/Button.js ================================================ class Button extends Element { constructor() { super(); this.defaultStyle = { display: 'flex', width: 100, height: 30, color: 'white', fontSize: 12, flexWrap: 'wrap', backgroundColor: 'gray', borderWidth: 1, borderColor: '#ffffff', flexDirection: 'row', alignItems: 'center', justifyContent: 'center' } } render() { this.compatHTML(); var s = TemplateFill({ color: null, fontFamily: null, fontSize: null, fontStyle: null, fontWeight: null, letterSpacing: null, textAlign: null, textDecorationLine: null, textDecorationStyle: null, textDecorationColor: null, writingDirection: null, flex: 1, flexWrap: 'wrap', textAlign: 'center' }, this.htmlProps.style); var realStyle = htmlCssParser.filterTextStyle(s); return ( {this.handleEvent.call(this, {type: 'click'})}}> {this.props.children} ); } } module.exports = Button; ================================================ FILE: reactnative/common/rn/Carousel.js ================================================ var PAGE_CHANGE_DELAY = 4000; /** * Animates pages in cycle (loop possible if children count > 1) */ class Carousel extends Element{ constructor(){ super(); } componentWillMount(){ super.componentWillMount && super.componentWillMount(); if (!!this.props.children) { var childrenCount = this.props.children.length; this.state = { contentOffset: {x: 0, y: 0}, currentPage: childrenCount > 1 ? 1 : 0, hasChildren: true, size: { width: 0, height: 0 } }; } else { this.state = { hasChildren: false, size: { width: 0, height: 0 } } } } componentDidMount(){ super.componentDidMount && super.componentDidMount(); if (this.state.hasChildren) { this._setUpTimer(); } } _onScrollBegin(event) { this.clearTimeout(this.timer); } _onScrollEnd(event) { this._setUpTimer(); var offset = Object.assign({}, event.nativeEvent.contentOffset); var childrenCount = this.props.children.length, size = this.state.size; if (offset.x === 0) { offset.x = childrenCount * size.width; } else if (offset.x == (childrenCount+1)*size.width) { offset.x = size.width; } this._calculateCurrentPage(offset.x); this.setState({contentOffset: offset}); } _onLayout() { let self = this; this.refs.container.measure(function(x, y, w, h, px, py) { self.setState({ contentOffset: { x: w }, size: { width: w, height: h} }); }); } _setUpTimer() { // only for cycling if (this.props.autoplay && this.props.children.length > 1) { this.clearTimeout(this.timer); this.timer = this.setTimeout(this._animateNextPage, this.props.delay); } } _animateNextPage() { var k = this.state.currentPage; var size = this.state.size; k++; this.setState({currentPage: k}); this.refs.scrollView.scrollTo(0, k*size.width); this._setUpTimer(); } _calculateCurrentPage(offset) { var size = this.state.size; var page = Math.floor((offset - size.width/2) / size.width) + 1; this.setState({currentPage: page}); } // TODO: add optional `dots` for displaying current page (like pageControl) render() { //this.compatHTML(); var pages = [], contents, containerProps; var size = this.state.size; containerProps = { ref: 'container', onLayout: this._onLayout.bind(this), style: [this.props.style] }; if (!this.state.hasChildren) { contents = ( You are supposed to add children inside Carousel ); } var children = this.props.children; // to make infinite pages structure like this is needed: 3-1-2-3-1 // add last one at the 1st place if (children.length >= 1) { pages.push(children[children.length-1]); } // add all pages for (var i=0; i= 1) { pages.push(children[0]); } pages = pages.map((page, i) => { return ( {page} ); }); contents = ( 1?2:0)), height: size.height } ]} > {pages} ); return ( {contents} ); } } var styles = StyleSheet.create({ horizontalScroll: { position:'absolute' } }); Carousel.propTypes = { children: React.PropTypes.node.isRequired, delay: React.PropTypes.number, style: View.propTypes.style, pageStyle: View.propTypes.style, contentContainerStyle: View.propTypes.style, autoplay: React.PropTypes.bool } Carousel.defaultProps = { delay: PAGE_CHANGE_DELAY, autoplay: true } module.exports = Carousel; ================================================ FILE: reactnative/common/rn/Div.js ================================================ class Div extends Element { constructor() { super(); this.defaultStyle = { color: 'black' } } render(){ return super.render(); } } module.exports = Div; ================================================ FILE: reactnative/common/rn/Element.js ================================================ String.prototype.capitalizeFirstLetter = function() { return this.charAt(0).toUpperCase() + this.slice(1); } // class Element extends React.Component { constructor() { super(); this.state = this.state || {}; this.events = { onClick : React.PropTypes.func, onDbClick: React.PropTypes.func, // //onAbort: React.PropTypes.func, //onError: React.PropTypes.func, // onFocus: React.PropTypes.func, onSelect: React.PropTypes.func, onBlur: React.PropTypes.func, // onLoad: React.PropTypes.func, onChange: React.PropTypes.func, onResize: React.PropTypes.func, onUnLoad: React.PropTypes.func, // //onKeyDown: React.PropTypes.func, //onKeyPress: React.PropTypes.func, //onKeyUp: React.PropTypes.func, // //onMouseDown: React.PropTypes.func, //onMouseMove: React.PropTypes.func, //onMouseUp: React.PropTypes.func, // onTouchStart: React.PropTypes.func, onTouchMove: React.PropTypes.func, onTouchEnd: React.PropTypes.func, onTouchCancel: React.PropTypes.func, } for(var eventName in this.events){ this.eventHandle = this.eventHandle || {}; this.eventHandle[eventName] = []; } this.setTimeout = TimerMixin.setTimeout; this.clearTimeout = TimerMixin.clearTimeout; this.setInterval = TimerMixin.setInterval; this.clearInterval = TimerMixin.clearInterval; this.setImmediate = TimerMixin.setImmediate; this.clearImmediate = TimerMixin.clearImmediate; this.requestAnimationFrame = TimerMixin.requestAnimationFrame; this.cancelAnimationFrame = TimerMixin.cancelAnimationFrame; } _walkAndBindParent() { this.childNodes = this.props.children ? (({}).toString.call(this.props.children) == '[object Array]' ? this.props.children : (({}).toString.call(this.props.children) != '[object String]' ? [ this.props.children ] : null)) : this.props.children; var self = this; this.childNodes && this.childNodes.forEach(function(node){ if(node){ if(node._store){ try{ node._store.parentNode = self; node._store.inheritStyle = htmlCssParser.canInherit(self.htmlProps._css); }catch(e){ console.debug(e); } } } }) } parentNode(){ if(this._reactInternalInstance && this._reactInternalInstance._currentElement){ var o =this._reactInternalInstance._currentElement; if(o && o._store && o._store.parentNode){ return o._store.parentNode; }else if(this.props.parentNode){ return this.props.parentNode; } } return null; } getInheritStyle(){ if(this._reactInternalInstance && this._reactInternalInstance._currentElement){ var o =this._reactInternalInstance._currentElement; if(o && o._store && o._store.inheritStyle){ return o._store.inheritStyle; } } return {}; } tagName(){ return this.constructor.toString().match(/function (\w+)\(\)/)[1]; } /** * event */ addEventListener(eventName: String, handle: Function) { var eventName = 'on' + eventName.capitalizeFirstLetter(); this.eventHandle[eventName].push(handle); } removeEventListener(eventName: String, handle: Function) { var eventName = 'on' + eventName.capitalizeFirstLetter(); if(!handle) { this.eventHandle[eventName] = []; }else{ for(var i = 0, a = this.eventHandle[eventName]; i < a.length; i++) { if(a[i] == handle) { a.splice(i, 1); break; } } } } handleEvent(event: Event) { //dom 1 event var eventName = 'on' + event.type.capitalizeFirstLetter(); var handle = this[eventName]; handle && handle(event); //dom 2 event var self = this; self.eventHandle[eventName] && self.eventHandle[eventName].forEach(function(item, index){ item && item.call(self, event); }) //bubble if(event.bubbles){ var o; if(this._reactInternalInstance && this._reactInternalInstance._currentElement){ o = this._reactInternalInstance._currentElement; } o && o._store && o._store.parentNode && o._store.parentNode.handleEvent.apply(o._store.parentNode, arguments); } } componentWillMount(){ super.componentWillMount && super.componentWillMount(); } componentDidMount(){ super.componentDidMount && super.componentDidMount(); this.handleEvent.call(this, {type: 'load'}); } componentWillUnmount() { super.componentWillUnmount && super.componentWillUnmount(); //this.eventHandle = null; TimerMixin.componentWillUnmount.call(this); if(this.props.id){ delete DOMTREE_BYID[this.props.id]; } if(this.props.id){ delete DOMTREE_BYID[this.props.id]; } if(this.props.className) { var a = this.props.className.split(/\s+/); var self = this; a.forEach(function(i){ if(DOMTREE_BYCLASS[i].indexOf(self) > -1){ DOMTREE_BYCLASS[i].splice(DOMTREE_BYCLASS[i].indexOf(self), 1); } }); } this.handleEvent.call(this, {type: 'unload'}); } /** * render */ render() { this.compatHTML(); if(({}).toString.call(this.props.children)=='[object String]'){ return ( {this.handleEvent.call(this, new DomEvent({type: 'click', reactEvent: e}))}}> {this.handleEvent.call(this, new DomEvent({type: 'touchStart',reactEvent: e}));}} onTouchMove={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'touchMove',reactEvent: e}));}} onTouchEnd={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'touchEnd',reactEvent: e}));}} style={htmlCssParser.filterViewStyle(this.htmlProps.style)}> {this.state.children} ); }else if(({}).toString.call(this.props.children)=='[object Array]'){ var htmlChildren = []; var self= this; this.props.children.forEach(function(item, idx){ if(item){ if(({}).toString.call(item)=='[object String]'){ htmlChildren.push(React.createElement(Text, {style: TemplateFill({ color: null, fontFamily: null, fontSize: null, fontStyle: null, fontWeight: null, letterSpacing: null, textAlign: null, textDecorationLine: null, textDecorationStyle: null, textDecorationColor: null, writingDirection: null }, self.htmlProps.style), key: idx}, item)); }else{ htmlChildren.push(item); } } }); this.state.children = htmlChildren; return ( {this.handleEvent.call(this, new DomEvent({type: 'click', reactEvent: e}))}}> {this.handleEvent.call(this, new DomEvent({type: 'touchStart',reactEvent: e}));}} onTouchMove={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'touchMove',reactEvent: e}));}} onTouchEnd={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'touchEnd',reactEvent: e}));}} style={htmlCssParser.filterViewStyle(this.htmlProps.style)}>{this.state.children} ); }else{ return ( {this.handleEvent.call(this, new DomEvent({type: 'click', reactEvent: e}))}}> {this.handleEvent.call(this, new DomEvent({type: 'touchStart',reactEvent: e}));}} onTouchMove={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'touchMove',reactEvent: e}));}} onTouchEnd={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'touchEnd',reactEvent: e}));}} style={htmlCssParser.filterViewStyle(this.htmlProps.style)} > {this.state.children} ); } } /** * 做html的兼容,比如style和dom事件 */ compatHTML(conf) { var self = this; self.state = self.state || {}; self.state.children = this.props.children; if(!this.htmlProps){ this.htmlProps = this.htmlProps || {}; for(var k in this.props){ if(k!='style'){ this.htmlProps[k] = this.props[k]; } } //Object.assign(this.htmlProps, this.props); } /** * reset Event Array */ for(var e in this.eventHandle){ this.eventHandle[e] = []; } for(var eventName in this.events){ var fn = this.props[eventName]; if(fn){ self.addEventListener(eventName.substring(2).capitalizeFirstLetter(), fn); } } /** * 默认字体使用rem */ if(!this.htmlProps._css){ this.defaultStyle = this.defaultStyle || {}; this.htmlProps._css = Object.assign({ fontSize: window.STYLESHEET.remUnit }, this.defaultStyle, this.getInheritStyle()); } //这边是css权重算法 if(this.htmlProps.className && !this.classList) { var a = this.htmlProps.className.split(/\s+/); this.classList = a; } if(this.classList && this.classList.length){ this.state.className = this.classList.join(' '); var self = this; this.classList.forEach(function(i){ /** * 加入className tree */ DOMTREE_BYCLASS[i] = DOMTREE_BYCLASS[i] || []; if(DOMTREE_BYCLASS[i].indexOf(self) == -1){ DOMTREE_BYCLASS[i].push(self); } /** * 开始对于className的继承的处理 */ Object.assign(self.htmlProps._css, STYLESHEET.sheets['.' + i]); if(STYLESHEET.sheets['+.' + i] && STYLESHEET.sheets['+.' + i].length){ for(var j = 0; j < STYLESHEET.sheets['+.' + i].length; j++){ var css = STYLESHEET.sheets['+.' + i][j].inherit.slice(); var find = false; var par = self; var maxLoop = 999; while(css.length && (par = par.parentNode()) && (maxLoop> 0)){ maxLoop--; var cur = css[css.length -1]; if(/^\./.test(cur)){ if(par.classList && par.classList.indexOf(cur.substring(1)) > -1){ css.pop(); if(css.length == 0){ find = true; break; } } }else if(/^#/.test(cur)){ if(par.props.id == cur.substring(1)){ css.pop(); if(css.length == 0){ find = true; break; } } }else if(/^[A-Z]/.test(cur)){ if(par.tagName() == cur){ css.pop(); if(css.length == 0){ find = true; break; } } } } if(find){ Object.assign(self.htmlProps._css, STYLESHEET.sheets['+.' + i][j].css); } } } }); } if(this.classList){ var allEnumClass = allEnum(this.classList); function allEnum(a){ var re = []; for(var i = 0; i < a.length; i++){ o(i, a, re, a[i]); function o(start, array, re, prefix){ for(var j = start + 1; j < array.length; j++){ var newK = '.' + prefix.toString() + '.' + array[j].toString(); re.push(newK); o(j, array, re, newK); } } } return re; } /** * 我觉得这里面还是有问题的,我们应该实现一个linkedHashMap保持原来的css的插入顺序才可以,现在这样的权重还是有点问题 */ allEnumClass.forEach(function(item){ if(STYLESHEET.sheets[item]){ Object.assign(self.htmlProps._css, STYLESHEET.sheets[item]); } }) } if(this.props.id){ DOMTREE_BYID[this.props.id] = this; /** * 权重id的权重大于className */ Object.assign(self.htmlProps._css, STYLESHEET.sheets['#' + this.props.id]); } /** * 直接赋值的样式权重最大 */ if(!this.state.inlineStyle){ /* if(this.props.style!= null && '0' in this.props.style){ var re = {}; for(var k in this.props.style){ Object.assign(re, this.props.style[k]); } this.state.inlineStyle = re; }else{ this.state.inlineStyle = this.props.style; } */ this.state.inlineStyle = this.props.style; } if(this.state.inlineStyle){ Object.assign(this.htmlProps._css, this.state.inlineStyle); } if(this.htmlProps._css) { this.htmlProps.style = htmlCssParser.parse(this.htmlProps._css, this.tagName()); } // if(conf && conf.isBubble == false){ }else{ this._walkAndBindParent(); } } _defineParentNode(parentNode){ if(this._reactInternalInstance._currentElement._store){ this._reactInternalInstance._currentElement._store.parentNode = parentNode; } } /** * reactnative版本的getComputedStyle,回调处理 */ offset(){ return new Promise((resolve, reject) => { UIManager.measure(React.findNodeHandle(this), (x, y, width, height, left, top) => { resolve({ x: x, y: y, left: left, top: top, width: width, height: height }); }); }); } /** * class */ addClass(cls){ this.classList = this.classList || []; var idx = this.classList.indexOf(cls); if(idx > -1){ this.classList.splice(idx, 1); } this.classList.push(cls); this.setState({ className: this.classList.join(' ') }); } removeClass(cls){ this.classList = this.classList || []; var idx = this.classList.indexOf(cls); if(idx > -1){ this.classList.splice(idx, 1); this.setState({ className: this.classList.join(' ') }); } } hasClass(cls){ this.classList = this.classList || []; var idx = this.classList.indexOf(cls); if(idx > -1){ return true; } return false; } css(styleName, styleValue){ if(arguments.length == 0){ return this.htmlProps._css; }else if(arguments.length == 1){ if(({}).toString.call(styleName) == '[object String]'){ return this.htmlProps._css[styleName]; }else{ var newInlineStyle = Object.assign({}, this.state.inlineStyle, styleName); this.setState({inlineStyle: newInlineStyle}); } }else if(arguments.length == 2){ var t = {}; t[styleName] = styleValue; var newInlineStyle = Object.assign({}, this.state.inlineStyle, t); this.setState({inlineStyle: newInlineStyle}); } } /** * dom */ html(o){ if(o){ this.setState({ children: o }) }else{ return this.state.children; } } attr(k, v){ if(arguments.length ==2){ this.htmlProps[k] = v; this.render(); }else if(arguments.length == 1){ return this.htmlProps[k]; } } append(o){ var children = this.state.children.slice(0).concat([o]); this.setState({ children: children }) } before(o){ var children = [o].concat(this.state.children.slice(0)); this.setState({ children: children }) } on(eventType, fn){ this.addEventListener(eventType, fn); } off(eventType, fn){ this.removeEventListener(eventType, fn); } animate(config){ animation.motion(Object.assign(config, {el: this})); } } module.exports = Element; ================================================ FILE: reactnative/common/rn/Header.js ================================================ class Header extends Element { constructor() { super(); this.state = { title: '', leftButton: { title: '返回', handler: function(){}, image: null }, rightButton: { title: '', handler: function(){}, image: null } } } setTitle(title){ this.state.title = title; } setLeftButton(o){ this.state.leftButton = o; } setRightButton(o){ this.state.rightButton = o; } componentWillMount(){ super.componentWillMount && super.componentWillMount.call(this); if(this.props.title){ this.state.title = this.props.title; } if('leftButton' in this.props){ if(this.props.leftButton){ this.state.leftButton = this.state.leftButton || {}; Object.assign(this.state.leftButton, this.props.leftButton); }else{ this.state.leftButton = null; } } if('rightButton' in this.props){ if(this.props.rightButton){ this.state.rightButton = this.state.rightButton || {}; Object.assign(this.state.rightButton, this.props.rightButton); }else{ this.state.rightButton = null; } } } render() { this.compatHTML(); var self = this; if(this.props.children){ return (
{this.props.children}
) }else{ return (
{self.state.title}
{ self.state.leftButton ?
{ self.state.leftButton.image? : null } {self.state.leftButton.title}
: null } { self.state.rightButton ?
{ self.state.rightButton.image? : null } {self.state.rightButton.title}
: null }
) } } } module.exports = Header; ================================================ FILE: reactnative/common/rn/HtmlCssParser.js ================================================ class HtmlCssParser{ constructor(){ } parse(cssObject, tagName){ var htmlCssObj = {}; for (var k in cssObject){ var v = cssObject[k]; if(/(.+)(rem)/i.test(v)){ // v = window.STYLESHEET.remUnit * parseFloat(v.match(/(.+)(rem)/)[1]); v = parseFloat(v); }else if(/(.+)(em)/i.test(v)){ // v = window.STYLESHEET.emUnit * parseFloat(v.match(/(.+)(em)/)[1]); v = parseFloat(v); }else if(/(.+)(%)/.test(v)){ if(/height/i.test(k)){ v = Dimensions.get('window').height * parseFloat(v.match(/(.+)(%)/)[1]) * 0.01 }else{ v = Dimensions.get('window').width * parseFloat(v.match(/(.+)(%)/)[1]) * 0.01 } }else if(/(\d+(\.\d+)?)px/.test(v)){ v = v.replace(/(\d+(\.\d+)?)px/g, function(all, m1){ var v = parseFloat(m1) * (3/4); if(v< 0.5)v=0.5; return v; }); v = parseFloat(v); }else if(/(\d+(\.\d+)?)pt/.test(v)){ v = v.replace(/(\d+(\.\d+)?)pt/g, function(all, m1){ return parseFloat(m1); }); v = parseFloat(v); }else if(/^\d+(\.\d+)?$/.test(v)){ v = parseFloat(v); } if(v== 'auto'){ }else if(k=='fontFamily'){ }else{ htmlCssObj[k] = v; } } //crack // return htmlCssObj; } filterViewStyle(m){ var n = {}; var removeList = ['fontSize', 'display', 'color', 'textAlign','lineHeight', 'fontWeight']; for(var p in m){ if(removeList.indexOf(p) == -1){ n[p] = m[p] } } return n; } filterTextStyle(m){ var n = {}; var removeList = ['display']; for(var p in m){ if(removeList.indexOf(p) == -1){ n[p] = m[p] } } return n; } canInherit(m){ var n = {}; var canI = ['fontSize', 'textAlign', 'color', 'lineHeight', 'fontWeight']; for(var p in m){ if(canI.indexOf(p) > -1){ n[p] = m[p] } } return n; } } module.exports = new HtmlCssParser(); ================================================ FILE: reactnative/common/rn/Img.js ================================================ class Img extends Element { render() { this.compatHTML(); delete this.htmlProps.style.fontSize; return } getRelativePath(path){ if(({}).toString.call(path)=='[object String]'){ return {uri: window.IMG_CDN_PREFIX && path.indexOf('http:')!=0 ? (window.IMG_CDN_PREFIX + path) : path}; }else{ return path; } } } module.exports = Img; ================================================ FILE: reactnative/common/rn/Input.js ================================================ class Input extends Element { constructor(){ super(); this.defaultStyle = { width: 150, height: 30, borderBottomColor: 'black', borderWidth: 1 } this.value = ''; } render() { this.compatHTML(); if(this.props.value){ this.value = this.props.value; } return ( {this.handleEvent.call(this, new DomEvent({type: 'change', reactEvent: e}))}} onFocus={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'focus', reactEvent: e}))}} onBlur={(e)=>{this.handleEvent.call(this, new DomEvent({type: 'blur', reactEvent: e}))}} /> ); } _setValue(v){ this.value = v; } val(v){ if(v!=null){ this.value = v; } if(v==undefined){ return this.value; } } } module.exports = Input; ================================================ FILE: reactnative/common/rn/Nav.js ================================================ class Nav extends Element { render () { this.compatHTML(); return ; } } module.exports = Nav; ================================================ FILE: reactnative/common/rn/RightSliderMenu.js ================================================ class RightSliderMenu extends Element{ constructor(){ super(); this.state = { delay: 30, menuWidth: 50 } } _onScrollBegin(){ if(this.props.onTouchStart){ this.props.onTouchStart(); } console.debug(this) this.clearTimeout(this.timer); } _onScrollEnd(){ console.debug(this) this.clearTimeout(this.timer); this.timer = this.setTimeout(this._animate, this.state.delay); } _animate(){ console.debug(this.dragEndX); console.debug(this.dragStartX) var distance = this.dragEndX - this.dragStartX; console.debug(distance) if(distance < -(this.state.menuWidth/2)){ console.debug(1); this.refs['scrollView'].scrollTo(0, this.state.menuWidth) }else{ console.debug(2); this.refs['scrollView'].scrollTo(0, 0) } } _onTouchStart(e){ this.dragStartX = e.nativeEvent.pageX; } _onTouchEnd(e){ this.dragEndX = e.nativeEvent.pageX; this.clearTimeout(this.timer); this.timer = this.setTimeout(this._animate, this.state.delay); } render(){ this.compatHTML(); return ( {this.props.children} ); } } module.exports = RightSliderMenu; ================================================ FILE: reactnative/common/rn/SimpleListView.js ================================================ class SimpleListView extends Element { render() { this.compatHTML(); return ; } } SimpleListView.initDataSource = () => { var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); var defaultDS = ds.cloneWithRows([]); return defaultDS; } module.exports = SimpleListView; ================================================ FILE: reactnative/common/rn/Span.js ================================================ var DomEvent = require('../DomEvent'); class Span extends Element { render() { this.compatHTML(); return ( ); } } module.exports = Span; ================================================ FILE: reactnative/common/rn/Tab.js ================================================ class Tab extends Element { render() { this.compatHTML(); return ( ); } } module.exports = Tab; ================================================ FILE: reactnative/common/rn/TabItem.js ================================================ class TabItem extends Element { render() { this.compatHTML(); return ( {this.props.children} ); } } module.exports = TabItem; ================================================ FILE: reactnative/common/rn/TabSlider.js ================================================ class SegmentControl extends Element { _onChange(event: Event) { this.props.config.onChange && this.props.config.onChange.call(this, event.nativeEvent.segmentSelectedIndex); } render(){ this.compatHTML(); return ; } } SegmentControl.propTypes = { config: React.PropTypes.shape({ itemNameArray: React.PropTypes.array.isRequired, itemFontSize: React.PropTypes.number.isRequired, contentHeight:React.PropTypes.number.isRequired, silderViewHeight: React.PropTypes.number.isRequired, selectedColor: React.PropTypes.color, normalColor: React.PropTypes.color, selectedIndex:React.PropTypes.number.isRequired, }) }; var CTRIPSegmentViewControl = requireNativeComponent('CTRIPSegmentViewControl', SegmentControl, { nativeOnly: { onChange: true } }); module.exports = SegmentControl; ================================================ FILE: reactnative/css/cxylhl/index.js ================================================ var styles = { "body *": { "fontFamily": "\"Consolas\",\"Microsoft Yahei\", Arial, sans-serif" }, "body": { "backgroundColor": "white", "margin": "0", "padding": "0" }, ".header": { "flexDirection": "row" }, ".sup": { "fontSize": "0.4rem", "backgroundColor": "yellow", "color": "red" }, ".container": {}, ".container .title": { "color": "#bbbbbb", "fontWeight": "bold", "backgroundColor": "#555555", "paddingTop": "5px", "paddingBottom": "5px", "paddingRight": "15px", "paddingLeft": "15px" }, ".adlink": { "textAlign": "center", "fontSize": "11pt" }, ".adlink a": { "color": "#666666", "fontWeight": "bold", "marginBottom": "10px", "backgroundColor": "#eeeeee", "borderWidth": "1px", "borderStyle": "solid", "borderColor": "#dddddd", "borderRadius": "4px", "padding": "10pt", "marginTop": "10pt" }, ".date": { "fontSize": "17pt", "fontWeight": "bold", "lineHeight": "30pt", "textAlign": "center" }, ".split": { "height": "1px" }, ".clear": { "height": "1px" }, ".good": { "flexDirection": "row", "backgroundColor": "#ffee44" }, ".bad": { "flexDirection": "row", "backgroundColor": "#ff4444" }, ".good .title": { "flex": "0.5", "fontWeight": "bold", "fontSize": "2rem", "backgroundColor": "#ffee44", "alignSelf": "center", "textAlign": "center" }, ".bad .title": { "flex": "0.5", "fontWeight": "bold", "fontSize": "2rem", "backgroundColor": "#ff4444", "color": "#ffffff", "alignSelf": "center", "textAlign": "center" }, ".good .title .title-text": {}, ".bad .title .title-text": {}, ".good .content": { "backgroundColor": "#ffffaa", "flex": "1", "padding": "10px" }, ".someday .good .title": { "backgroundColor": "#aaaaaa" }, ".bad .content": { "backgroundColor": "#ffddd3", "flex": "1", "padding": "10px" }, ".someday .bad .title": { "backgroundColor": "#666666", "color": "#ffffff" }, ".someday .good": { "backgroundColor": "#dddddd" }, ".someday .bad": { "backgroundColor": "#aaaaaa" }, ".content .name": { "height": "1.5rem", "justifyContent": "center", "fontSize": "1rem", "fontWeight": "bold", "color": "#444444" }, ".content .description": { "fontSize": "0.7rem", "fontWeight": "normal", "color": "#777777" }, ".Divne-tip": { "padding": "10px", "flexDirection": "row", "alignItems": "center" }, ".adDivnk": { "fontSize": "0.5rem" }, ".direction_value": { "color": "#4a44a4", "fontWeight": "bold" }, ".someday .direction_value": { "color": "#888888" }, ".goddes_value": { "color": "#f87f87" }, ".someday .goddes_value": { "color": "#777777" }, ".comment": { "fontSize": "11pt", "margin": "10px", "color": "#999999" }, ".spDivt": { "fontSize": "0.7rem" } } module.exports = styles; ================================================ FILE: reactnative/css/game/game2048.js ================================================ var styles = { ".container": { "paddingTop": "0", "paddingBottom": "0", "paddingRight": "20pt", "paddingLeft": "20pt" }, ".heading": { "height": "80pt", "marginTop": "40pt", "flexDirection": "row" }, ".heading .heading-title": { "fontSize": "48pt", "color": "#776E65", "fontWeight": "bold" }, ".heading .scores": { "flex": "1", "flexDirection": "row", "justifyContent": "flex-end", "flexWrap": "wrap", "alignItems": "flex-start" }, ".heading .container": { "backgroundColor": "#bbada0", "paddingLeft": "15pt", "paddingRight": "15pt", "paddingTop": "5pt", "paddingBottom": "5pt", "borderRadius": "3pt", "marginLeft": "5pt", "flexDirection": "column", "alignItems": "center" }, ".heading .container-title": { "color": "#eee4da", "textAlign": "center", "fontWeight": "bold", "fontSize": "12pt" }, ".heading .container-value": { "color": "#ffffff", "textAlign": "center", "fontSize": "24pt", "fontWeight": "bold" }, ".abovegame": { "flexDirection": "row", "flexWrap": "nowrap", "marginTop": "5pt" }, ".abovegame .textContainer": { "flex": "1", "marginRight": "10pt" }, ".abovegame .text": { "color": "#776E65", "fontSize": "16pt", "lineHeight": "26pt" }, ".abovegame .boldText": { "fontWeight": "bold" }, ".abovegame .newGameContainer": { "backgroundColor": "#8f7a66", "paddingTop": "15pt", "paddingBottom": "15pt", "paddingRight": "10pt", "paddingLeft": "10pt", "borderRadius": "3pt" } } module.exports = styles; ================================================ FILE: reactnative/css/jqueryapi.js ================================================ var styles = { ".cls1": { "color": "red" }, ".cls2": { "color": "yellow" } } module.exports = styles; ================================================ FILE: reactnative/css/lightningStorm.js ================================================ var styles = { ".custom-native-header": { "marginTop": "20pt" }, ".native-header": { "flexDirection": "row", "alignItems": "center", "justifyContent": "center", "height": "40pt", "color": "#ffffff", "backgroundColor": "rgb(9,159,222)", "marginTop": "20pt" }, ".native-header-box": { "flex": "1", "alignItems": "center", "justifyContent": "center" }, ".native-header-title": { "color": "#ffffff" }, ".native-header-leftButton": { "position": "absolute", "top": "0", "left": "10pt", "color": "black" }, ".native-header-rightButton": { "position": "absolute", "right": "10pt", "top": "0", "backgroundColor": "white" } } module.exports = styles; ================================================ FILE: reactnative/css/vsImgList.js ================================================ var styles = { ".imgList": { "position": "relative" }, ".float-bg": { "backgroundColor": "gray", "color": "#000000", "opacity": "0.2", "height": "4rem", "width": "100%", "position": "absolute", "bottom": "0", "left": "0" } } module.exports = styles; ================================================ FILE: reactnative/css/vsIndex.js ================================================ var styles = { "body": { "margin": "0", "padding": "0" }, "#J-block-test": { "backgroundColor": "yellow", "height": "2rem" }, ".j-j_j": { "color": "red", "flexDirection": "row", "justifyContent": "center", "alignItems": "center" }, ".i_i-i": { "color": "black" }, ".j-j_j.i_i-i": { "color": "green" }, ".index-contains": { "flex": "1", "alignItems": "center" }, ".index-goDiv": { "flexDirection": "row", "alignItems": "center", "padding": "10", "justifyContent": "center" }, ".index-btn": { "flex": "1", "alignItems": "center", "justifyContent": "center", "flexDirection": "row", "padding": "10pt" }, ".index-list-row .index-list-leftImg": { "width": "3rem", "paddingTop": ".5rem", "flexDirection": "row", "justifyContent": "center" }, ".index-list-leftImg-img": { "width": "2rem", "height": "2rem" }, ".index-list-row": { "flexDirection": "row", "justifyContent": "flex-start" }, ".index-list-row .index-list-rightBox": { "flex": "1" }, ".index-list-row .index-list-rightBox-row-desc": { "backgroundColor": "red" }, ".index-list-complexRow .index-list-rightBox .index-list-rightBox-row": { "backgroundColor": "green", "color": "red" }, "#jjj": { "backgroundColor": "green" }, "SimpleListView": { "backgroundColor": "yellow" } } module.exports = styles; ================================================ FILE: reactnative/cxylhl.js ================================================ includeCSS("require('./css/cxylhl/index')"); /* * 注意:本程序中的“随机”都是伪随机概念,以当前的天为种子。 */ function random(dayseed, indexseed) { var n = dayseed % 11117; for (var i = 0; i < 100 + indexseed; i++) { n = n * n; n = n % 11117; // 11117 是个质数 } return n; } var today = new Date(); var iday = today.getFullYear() * 10000 + (today.getMonth() + 1) * 100 + today.getDate(); var weeks = ["日","一","二","三","四","五","六"]; var directions = ["北方","东北方","东方","东南方","南方","西南方","西方","西北方"]; var activities = [ {name:"写单元测试", good:"写单元测试将减少出错",bad:"写单元测试会降低你的开发效率"}, {name:"洗澡", good:"你几天没洗澡了?",bad:"会把设计方面的灵感洗掉", weekend: true}, {name:"锻炼一下身体", good:"",bad:"能量没消耗多少,吃得却更多", weekend: true}, {name:"抽烟", good:"抽烟有利于提神,增加思维敏捷",bad:"除非你活够了,死得早点没关系", weekend: true}, {name:"白天上线", good:"今天白天上线是安全的",bad:"可能导致灾难性后果"}, {name:"重构", good:"代码质量得到提高",bad:"你很有可能会陷入泥潭"}, {name:"使用%t", good:"你看起来更有品位",bad:"别人会觉得你在装逼"}, {name:"跳槽", good:"该放手时就放手",bad:"鉴于当前的经济形势,你的下一份工作未必比现在强"}, {name:"招人", good:"你面前这位有成为牛人的潜质",bad:"这人会写程序吗?"}, {name:"面试", good:"面试官今天心情很好",bad:"面试官不爽,会拿你出气"}, {name:"提交辞职申请", good:"公司找到了一个比你更能干更便宜的家伙,巴不得你赶快滚蛋",bad:"鉴于当前的经济形势,你的下一份工作未必比现在强"}, {name:"申请加薪", good:"老板今天心情很好",bad:"公司正在考虑裁员"}, {name:"晚上加班", good:"晚上是程序员精神最好的时候",bad:"", weekend: true}, {name:"在妹子面前吹牛", good:"改善你矮穷挫的形象",bad:"会被识破", weekend: true}, {name:"撸管", good:"避免缓冲区溢出",bad:"强撸灰飞烟灭", weekend: true}, {name:"浏览成人网站", good:"重拾对生活的信心",bad:"你会心神不宁", weekend: true}, {name:"命名变量\"%v\"", good:"",bad:""}, {name:"写超过%l行的方法", good:"你的代码组织的很好,长一点没关系",bad:"你的代码将混乱不堪,你自己都看不懂"}, {name:"提交代码", good:"遇到冲突的几率是最低的",bad:"你遇到的一大堆冲突会让你觉得自己是不是时间穿越了"}, {name:"代码复审", good:"发现重要问题的几率大大增加",bad:"你什么问题都发现不了,白白浪费时间"}, {name:"开会", good:"写代码之余放松一下打个盹,有益健康",bad:"小心被扣屎盆子背黑锅"}, {name:"打DOTA", good:"你将有如神助",bad:"你会被虐的很惨", weekend: true}, {name:"晚上上线", good:"晚上是程序员精神最好的时候",bad:"你白天已经筋疲力尽了"}, {name:"修复BUG", good:"你今天对BUG的嗅觉大大提高",bad:"新产生的BUG将比修复的更多"}, {name:"设计评审", good:"设计评审会议将变成头脑风暴",bad:"人人筋疲力尽,评审就这么过了"}, {name:"需求评审", good:"",bad:""}, {name:"上微博", good:"今天发生的事不能错过",bad:"今天的微博充满负能量", weekend: true}, {name:"上AB站", good:"还需要理由吗?",bad:"满屏兄贵亮瞎你的眼", weekend: true}, {name:"玩FlappyBird", good:"今天破纪录的几率很高",bad:"除非你想玩到把手机砸了", weekend: true} ]; var specials = [ {date:20140214, type:'bad', name:'待在男(女)友身边', description:'脱团火葬场,入团保平安。'} ]; var tools = ["Eclipse写程序", "MSOffice写文档", "记事本写程序", "Windows8", "Linux", "MacOS", "IE", "Android设备", "iOS设备"]; var varNames = ["jieguo", "huodong", "pay", "expire", "zhangdan", "every", "free", "i1", "a", "virtual", "ad", "spider", "mima", "pass", "ui"]; var drinks = ["水","茶","红茶","绿茶","咖啡","奶茶","可乐","鲜奶","豆奶","果汁","果味汽水","苏打水","运动饮料","酸奶","酒"]; function is_someday() { return today.getMonth() == 5 && today.getDate() == 4; } function getTodayString() { return "今天是" + today.getFullYear() + "年" + (today.getMonth() + 1) + "月" + today.getDate() + "日 星期" + weeks[today.getDay()]; } function star(num) { var result = ""; var i = 0; while (i < num) { result += "★"; i++; } while(i < 5) { result += "☆"; i++; } return result; } // 生成今日运势 function pickTodaysLuck(good, bad) { var _activities = filter(activities); var numGood = random(iday, 98) % 3 + 2; var numBad = random(iday, 87) % 3 + 2; var eventArr = pickRandomActivity(_activities, numGood + numBad); var specialSize = pickSpecials(); for (var i = 0; i < numGood; i++) { good.push(eventArr[i]); } for (var i = 0; i < numBad; i++) { bad.push(eventArr[numGood + i]); } } // 去掉一些不合今日的事件 function filter(activities) { var result = []; // 周末的话,只留下 weekend = true 的事件 if (isWeekend()) { for (var i = 0; i < activities.length; i++) { if (activities[i].weekend) { result.push(activities[i]); } } return result; } return activities; } function isWeekend() { return today.getDay() == 0 || today.getDay() == 6; } // 添加预定义事件 function pickSpecials() { var specialSize = [0,0]; for (var i = 0; i < specials.length; i++) { var special = specials[i]; if (iday == special.date) { if (special.type == 'good') { specialSize[0]++; addToGood({name: special.name, good: special.description}); } else { specialSize[1]++; addToBad({name: special.name, bad: special.description}); } } } return specialSize; } // 从 activities 中随机挑选 size 个 function pickRandomActivity(activities, size) { var picked_events = pickRandom(activities, size); for (var i = 0; i < picked_events.length; i++) { picked_events[i] = parse(picked_events[i]); } return picked_events; } // 从数组中随机挑选 size 个 function pickRandom(array, size) { var result = []; for (var i = 0; i < array.length; i++) { result.push(array[i]); } for (var j = 0; j < array.length - size; j++) { var index = random(iday, j) % result.length; result.splice(index, 1); } return result; } // 解析占位符并替换成随机内容 function parse(event) { var result = {name: event.name, good: event.good, bad: event.bad}; // clone if (result.name.indexOf('%v') != -1) { result.name = result.name.replace('%v', varNames[random(iday, 12) % varNames.length]); } if (result.name.indexOf('%t') != -1) { result.name = result.name.replace('%t', tools[random(iday, 11) % tools.length]); } if (result.name.indexOf('%l') != -1) { result.name = result.name.replace('%l', (random(iday, 12) % 247 + 30).toString()); } return result; } // 添加到“宜” function addToGood(event) { $('.good .content ul').append('
  • ' + event.name + '
    ' + event.good + '
  • '); } // 添加到“不宜” function addToBad(event) { $('.bad .content ul').append('
  • ' + event.name + '
    ' + event.bad + '
  • '); } (class CXYLHL extends App { constructor(){ super(); this.state = { bodyClass: '' }; if (is_someday()) { this.state.bodyClass = 'someday' } this.state.good = []; this.state.bad = []; pickTodaysLuck(this.state.good, this.state.bad); } acomponentDidMount(){ pickTodaysLuck(); } render() { return (
    程序员老黄历
    beta
    {getTodayString()}
    { this.state.good.map(function(event, i){ return (
    {event.name}
    {event.good}
    ); }) }
    不宜
    { this.state.bad.map(function(event, i){ return (
    {event.name}
    {event.good}
    ); }) }
    座位朝向:面向{directions[random(iday, 2) % directions.length]}写程序,BUG 最少。 今日宜饮:{pickRandom(drinks,2).join(',')} 女神亲近指数:{star(random(iday, 6) % 5 + 1)}
    本老黄历尚处于beta阶段,作者随时会修改,所以如果上午看到的内容跟下午不同,请勿惊慌;
    本老黄历仅面向程序员;
    本老黄历内容是程序生成的,因为只有这样程序员才会信。
    ); } }).run(); ================================================ FILE: reactnative/example_addEventListener.js ================================================ import './common/LightningStorm'; (class TestPage extends App{ componentDidMount(){ $('#J2').addEventListener('click', function(){ alert(3); }) } render(){ return (
    这是一个addEventListener的例子,并且支持冒泡,你可以修改index.ios.js,删除index,改成import这个例子的
    ); } }).run(); ================================================ FILE: reactnative/example_animation.js ================================================ import './common/LightningStorm'; var anim = require('./common/Animation'); (class Text extends App{ componentDidMount(){ $('#J1').animate({ duration : 1000, from : { position: 'absolute', top: '0pt', left: 0, }, to : { top: '100pt', left: '100pt' } }) } render(){ return (
    zxczxc
    ) } }).run(); ================================================ FILE: reactnative/example_formElement.js ================================================ import './common/LightningStorm'; (class TestPage extends App{ componentDidMount(){ setTimeout(async ()=>{ var a= await $('#J1').measure(); console.debug(a); },0); } render(){ return (
    这是一个表单的例子,你可以修改index.ios.js,删除index,改成import这个例子的
    input text
    button
    ); } }).run(); ================================================ FILE: reactnative/example_jqueryapi.js ================================================ import './common/LightningStorm'; includeCSS("require('./css/jqueryapi')"); (class TestPage extends App{ render(){ return (
    {alert(1)}}>
    {alert(2)}}> 对于jQuery API的测试,你可以测试这个节点有哪些常用的api可以操作
    ) } btn1(){ $('#J2').addClass('cls2'); console.debug($('#J2').classList) } btn2(){ $('#J2').addClass('cls1'); console.debug($('#J2').classList) } btn3(){ $('#J2').removeClass('cls2'); console.debug($('#J2').classList) } btn4(){ $('#J2').removeClass('cls1'); console.debug($('#J2').classList) } }).run(); ================================================ FILE: reactnative/example_listview.js ================================================ includeCSS("require('./css/vsIndex')"); class vsIndex extends Element { constructor(){ super(); this.state = { dataSource: SimpleListView.initDataSource(), } } render() { return (
    测试水平居中垂直居中
    ); } componentDidMount(){ var self = this; fetch('http://statics1.jiaru.club/react-native-example/list.js', {method:'get',headers:{'Content-Type':'application/json;charset=utf-8'}, //body: [''].join('') } ).then(function(req){ req.json().then(function(res){ var o = self.state.dataSource.cloneWithRows(res.list); self.setState({ dataSource: o }); }) }) } _renderRow(row, sid, rowid){ return ; } } class Row extends Element{ constructor(){ super(); this.state = { numberOfLines: 3 } } render(){ var row = this.props.data[0]; var rowid = this.props.data[2]; return (
    姓名: {row.name}
    简介: {row.desc}
    ); } collapse(){ if(this.state.numberOfLines == 3){ this.setState({ numberOfLines: null }) }else{ this.setState({ numberOfLines: 3 }) } } jumpImgList(){ pageRoute.push({ page: require('./vsImgList'), a: 1, b: 2, c: 3 }) } } module.exports = vsIndex; ================================================ FILE: reactnative/example_localStorage.js ================================================ import './common/LightningStorm'; (class TestPage extends App{ render(){ return (
    这是一个localStorage的例子,你可以修改index.ios.js,删除index,改成import这个例子的
    key: value:
    -----------
    ); } async testLocalStorage(){ console.debug('key is',$('#J_k').value); var key = $('#J_k').val(); if(key){ console.debug('value is',$('#J_v').value); console.debug($('#J_v').value); await localStorage.setItem(key, $('#J_v').value); alert('save success!'); } } async loadLocalStorage(){ var c = await localStorage.json(); alert(JSON.stringify(c)); } }).run(); ================================================ FILE: reactnative/example_onclick.js ================================================ import './common/LightningStorm'; (class TestPage extends App{ render(){ return (
    {alert(1)}}>
    {alert(2)}}> 这是一个点击事件的例子,并且支持冒泡,你可以修改index.ios.js,删除index,改成import这个例子的
    ); } }).run(); ================================================ FILE: reactnative/example_ontouch.js ================================================ import './common/LightningStorm'; (class TestPage extends App{ render(){ return (
    {console.log(e)}}>
    {console.log(e)}}> 这是一个Touch的例子,并且支持冒泡,你可以修改index.ios.js,删除index,改成import这个例子的
    ); } }).run(); ================================================ FILE: reactnative/example_view.js ================================================ import './common/LightningStorm'; (class Test extends App{ constructor(){ super(); } render(){ return ( {console.debug(e)}} onTouchMove={(e)=>{console.debug(e)}}> qlwekqlw;jeqkwjelqwjelkqwjelkqwjlejqwlkjk ); } }).run(); ================================================ FILE: reactnative/index.android.js ================================================ /** * index.android.js文件变成了区分ios平台还是安卓平台的工具,主入口改成了index.js */ import './common/LightningStorm'; import './index.js'; ================================================ FILE: reactnative/index.ios.js ================================================ /** * index.ios.js文件变成了区分ios平台还是安卓平台的工具,主入口改成了index.js */ import './common/LightningStorm'; includeCSS("require('./css/lightningStorm')"); import './cxylhl.js'; ================================================ FILE: reactnative/index.js ================================================ /** * 定义公共的全局变量,比如图片使用的cdn地址 */ window.IMG_CDN_PREFIX = 'http://cdn.taobao.com/'; //导入UI的css includeCSS("require('./css/lightningStorm')"); /** * 首页的例子代码如下, 只是初始化一个导航栏,未来应该会包装掉这个导航栏 */ (class HomePage extends App{ render() { return ( { window.pageRoute = navigator; return React.createElement(route.page, Object.assign({navigator: navigator}, route)); }} /> ); } }).run(); ================================================ FILE: reactnative/ios/native/AppDelegate.h ================================================ /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import @interface AppDelegate : UIResponder @property (nonatomic, strong) UIWindow *window; @end ================================================ FILE: reactnative/ios/native/AppDelegate.m ================================================ /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import "AppDelegate.h" #import "RCTRootView.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURL *jsCodeLocation; /** * Loading JavaScript code - uncomment the one you want. * * OPTION 1 * Load from development server. Start the server from the repository root: * * $ npm start * * To run on device, change `localhost` to the IP address of your computer * (you can get this by typing `ifconfig` into the terminal and selecting the * `inet` value under `en0:`) and make sure your computer and iOS device are * on the same Wi-Fi network. */ jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"]; /** * OPTION 2 * Load from pre-bundled file on disk. The static bundle is automatically * generated by "Bundle React Native code and images" build step. */ // jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"native" initialProperties:nil launchOptions:launchOptions]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } @end ================================================ FILE: reactnative/ios/native/Base.lproj/LaunchScreen.xib ================================================ ================================================ FILE: reactnative/ios/native/Images.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "idiom" : "iphone", "size" : "29x29", "scale" : "2x" }, { "idiom" : "iphone", "size" : "29x29", "scale" : "3x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "2x" }, { "idiom" : "iphone", "size" : "40x40", "scale" : "3x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "icon-60@2x.png", "scale" : "2x" }, { "idiom" : "iphone", "size" : "60x60", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: reactnative/ios/native/Images.xcassets/Brand Assets.launchimage/Contents.json ================================================ { "images" : [ { "orientation" : "portrait", "idiom" : "iphone", "minimum-system-version" : "7.0", "scale" : "2x" }, { "orientation" : "portrait", "idiom" : "iphone", "minimum-system-version" : "7.0", "subtype" : "retina4", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: reactnative/ios/native/Images.xcassets/Contents.json ================================================ { "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: reactnative/ios/native/Images.xcassets/LaunchImage.launchimage/Contents.json ================================================ { "images" : [ { "orientation" : "portrait", "idiom" : "iphone", "extent" : "full-screen", "minimum-system-version" : "8.0", "subtype" : "736h", "scale" : "3x" }, { "orientation" : "landscape", "idiom" : "iphone", "extent" : "full-screen", "minimum-system-version" : "8.0", "subtype" : "736h", "scale" : "3x" }, { "orientation" : "portrait", "idiom" : "iphone", "extent" : "full-screen", "minimum-system-version" : "8.0", "subtype" : "667h", "scale" : "2x" }, { "orientation" : "portrait", "idiom" : "iphone", "extent" : "full-screen", "minimum-system-version" : "7.0", "scale" : "2x" }, { "orientation" : "portrait", "idiom" : "iphone", "extent" : "full-screen", "minimum-system-version" : "7.0", "subtype" : "retina4", "scale" : "2x" }, { "orientation" : "portrait", "idiom" : "iphone", "extent" : "full-screen", "scale" : "1x" }, { "orientation" : "portrait", "idiom" : "iphone", "filename" : "Default@2x.png", "extent" : "full-screen", "scale" : "2x" }, { "orientation" : "portrait", "idiom" : "iphone", "extent" : "full-screen", "subtype" : "retina4", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: reactnative/ios/native/Images.xcassets/icon-1024.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "scale" : "1x" }, { "idiom" : "universal", "filename" : "icon-1024@2x.png", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: reactnative/ios/native/Info.plist ================================================ CFBundleDevelopmentRegion zh_CN CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.0 CFBundleVersion 2 LSRequiresIPhoneOS NSAppTransportSecurity NSAllowsArbitraryLoads NSLocationWhenInUseUsageDescription UILaunchImages UILaunchImageName Default-568 UILaunchImageSize {320,568} UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities armv7 UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance ================================================ FILE: reactnative/ios/native/main.m ================================================ /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import #import "AppDelegate.h" int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } ================================================ FILE: reactnative/ios/native.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */; }; 00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */; }; 00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */; }; 00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */; }; 00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */; }; 00E356F31AD99517003FC87E /* nativeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* nativeTests.m */; }; 133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C398B91ACF4ADC00677621 /* libRCTLinking.a */; }; 139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */; }; 139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */; }; 13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.m */; }; 13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB11A68108700A75B9A /* LaunchScreen.xib */; }; 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; 13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; 146834051AC3E58100842450 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; }; 832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 832341B51AAA6A8300B99B32 /* libRCTText.a */; }; 84A404191C7EFBB100BCCEEA /* Default-568@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 84A404181C7EFBB100BCCEEA /* Default-568@2x.png */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */; proxyType = 2; remoteGlobalIDString = 134814201AA4EA6300B7C361; remoteInfo = RCTActionSheet; }; 00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */; proxyType = 2; remoteGlobalIDString = 134814201AA4EA6300B7C361; remoteInfo = RCTGeolocation; }; 00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */; proxyType = 2; remoteGlobalIDString = 58B5115D1A9E6B3D00147676; remoteInfo = RCTImage; }; 00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */; proxyType = 2; remoteGlobalIDString = 58B511DB1A9E6C8500147676; remoteInfo = RCTNetwork; }; 00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */; proxyType = 2; remoteGlobalIDString = 832C81801AAF6DEF007FA2F7; remoteInfo = RCTVibration; }; 00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */; proxyType = 1; remoteGlobalIDString = 13B07F861A680F5B00A75B9A; remoteInfo = native; }; 139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */; proxyType = 2; remoteGlobalIDString = 134814201AA4EA6300B7C361; remoteInfo = RCTSettings; }; 139FDEF31B06529B00C62182 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */; proxyType = 2; remoteGlobalIDString = 3C86DF461ADF2C930047B81A; remoteInfo = RCTWebSocket; }; 146834031AC3E56700842450 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; proxyType = 2; remoteGlobalIDString = 83CBBA2E1A601D0E00E9B192; remoteInfo = React; }; 78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */; proxyType = 2; remoteGlobalIDString = 134814201AA4EA6300B7C361; remoteInfo = RCTLinking; }; 832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */; proxyType = 2; remoteGlobalIDString = 58B5119B1A9E6C1200147676; remoteInfo = RCTText; }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ 008F07F21AC5B25A0029DE68 /* main.jsbundle */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = main.jsbundle; sourceTree = ""; }; 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTActionSheet.xcodeproj; path = "../node_modules/react-native/Libraries/ActionSheetIOS/RCTActionSheet.xcodeproj"; sourceTree = ""; }; 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTGeolocation.xcodeproj; path = "../node_modules/react-native/Libraries/Geolocation/RCTGeolocation.xcodeproj"; sourceTree = ""; }; 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTImage.xcodeproj; path = "../node_modules/react-native/Libraries/Image/RCTImage.xcodeproj"; sourceTree = ""; }; 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTNetwork.xcodeproj; path = "../node_modules/react-native/Libraries/Network/RCTNetwork.xcodeproj"; sourceTree = ""; }; 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTVibration.xcodeproj; path = "../node_modules/react-native/Libraries/Vibration/RCTVibration.xcodeproj"; sourceTree = ""; }; 00E356EE1AD99517003FC87E /* nativeTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = nativeTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 00E356F21AD99517003FC87E /* nativeTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = nativeTests.m; sourceTree = ""; }; 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTSettings.xcodeproj; path = "../node_modules/react-native/Libraries/Settings/RCTSettings.xcodeproj"; sourceTree = ""; }; 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTWebSocket.xcodeproj; path = "../node_modules/react-native/Libraries/WebSocket/RCTWebSocket.xcodeproj"; sourceTree = ""; }; 13B07F961A680F5B00A75B9A /* native.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = native.app; sourceTree = BUILT_PRODUCTS_DIR; }; 13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = native/AppDelegate.h; sourceTree = ""; }; 13B07FB01A68108700A75B9A /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AppDelegate.m; path = native/AppDelegate.m; sourceTree = ""; }; 13B07FB21A68108700A75B9A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; }; 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = native/Images.xcassets; sourceTree = ""; }; 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = native/Info.plist; sourceTree = ""; }; 13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = native/main.m; sourceTree = ""; }; 146833FF1AC3E56700842450 /* React.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = React.xcodeproj; path = "../node_modules/react-native/React/React.xcodeproj"; sourceTree = ""; }; 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTLinking.xcodeproj; path = "../node_modules/react-native/Libraries/LinkingIOS/RCTLinking.xcodeproj"; sourceTree = ""; }; 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTText.xcodeproj; path = "../node_modules/react-native/Libraries/Text/RCTText.xcodeproj"; sourceTree = ""; }; 84A404181C7EFBB100BCCEEA /* Default-568@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568@2x.png"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 00E356EB1AD99517003FC87E /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 146834051AC3E58100842450 /* libReact.a in Frameworks */, 00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */, 00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */, 00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */, 133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */, 00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */, 139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */, 832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */, 00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */, 139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 00C302A81ABCB8CE00DB3ED1 /* Products */ = { isa = PBXGroup; children = ( 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */, ); name = Products; sourceTree = ""; }; 00C302B61ABCB90400DB3ED1 /* Products */ = { isa = PBXGroup; children = ( 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */, ); name = Products; sourceTree = ""; }; 00C302BC1ABCB91800DB3ED1 /* Products */ = { isa = PBXGroup; children = ( 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */, ); name = Products; sourceTree = ""; }; 00C302D41ABCB9D200DB3ED1 /* Products */ = { isa = PBXGroup; children = ( 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */, ); name = Products; sourceTree = ""; }; 00C302E01ABCB9EE00DB3ED1 /* Products */ = { isa = PBXGroup; children = ( 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */, ); name = Products; sourceTree = ""; }; 00E356EF1AD99517003FC87E /* nativeTests */ = { isa = PBXGroup; children = ( 00E356F21AD99517003FC87E /* nativeTests.m */, 00E356F01AD99517003FC87E /* Supporting Files */, ); path = nativeTests; sourceTree = ""; }; 00E356F01AD99517003FC87E /* Supporting Files */ = { isa = PBXGroup; children = ( 00E356F11AD99517003FC87E /* Info.plist */, ); name = "Supporting Files"; sourceTree = ""; }; 139105B71AF99BAD00B5F7CC /* Products */ = { isa = PBXGroup; children = ( 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */, ); name = Products; sourceTree = ""; }; 139FDEE71B06529A00C62182 /* Products */ = { isa = PBXGroup; children = ( 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */, ); name = Products; sourceTree = ""; }; 13B07FAE1A68108700A75B9A /* native */ = { isa = PBXGroup; children = ( 008F07F21AC5B25A0029DE68 /* main.jsbundle */, 13B07FAF1A68108700A75B9A /* AppDelegate.h */, 13B07FB01A68108700A75B9A /* AppDelegate.m */, 13B07FB51A68108700A75B9A /* Images.xcassets */, 13B07FB61A68108700A75B9A /* Info.plist */, 13B07FB11A68108700A75B9A /* LaunchScreen.xib */, 13B07FB71A68108700A75B9A /* main.m */, ); name = native; sourceTree = ""; }; 146834001AC3E56700842450 /* Products */ = { isa = PBXGroup; children = ( 146834041AC3E56700842450 /* libReact.a */, ); name = Products; sourceTree = ""; }; 78C398B11ACF4ADC00677621 /* Products */ = { isa = PBXGroup; children = ( 78C398B91ACF4ADC00677621 /* libRCTLinking.a */, ); name = Products; sourceTree = ""; }; 832341AE1AAA6A7D00B99B32 /* Libraries */ = { isa = PBXGroup; children = ( 146833FF1AC3E56700842450 /* React.xcodeproj */, 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */, 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */, 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */, 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */, 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */, 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */, 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */, 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */, 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */, ); name = Libraries; sourceTree = ""; }; 832341B11AAA6A8300B99B32 /* Products */ = { isa = PBXGroup; children = ( 832341B51AAA6A8300B99B32 /* libRCTText.a */, ); name = Products; sourceTree = ""; }; 83CBB9F61A601CBA00E9B192 = { isa = PBXGroup; children = ( 84A404181C7EFBB100BCCEEA /* Default-568@2x.png */, 13B07FAE1A68108700A75B9A /* native */, 832341AE1AAA6A7D00B99B32 /* Libraries */, 00E356EF1AD99517003FC87E /* nativeTests */, 83CBBA001A601CBA00E9B192 /* Products */, ); indentWidth = 2; sourceTree = ""; tabWidth = 2; }; 83CBBA001A601CBA00E9B192 /* Products */ = { isa = PBXGroup; children = ( 13B07F961A680F5B00A75B9A /* native.app */, 00E356EE1AD99517003FC87E /* nativeTests.xctest */, ); name = Products; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 00E356ED1AD99517003FC87E /* nativeTests */ = { isa = PBXNativeTarget; buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "nativeTests" */; buildPhases = ( 00E356EA1AD99517003FC87E /* Sources */, 00E356EB1AD99517003FC87E /* Frameworks */, 00E356EC1AD99517003FC87E /* Resources */, ); buildRules = ( ); dependencies = ( 00E356F51AD99517003FC87E /* PBXTargetDependency */, ); name = nativeTests; productName = nativeTests; productReference = 00E356EE1AD99517003FC87E /* nativeTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 13B07F861A680F5B00A75B9A /* native */ = { isa = PBXNativeTarget; buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "native" */; buildPhases = ( 13B07F871A680F5B00A75B9A /* Sources */, 13B07F8C1A680F5B00A75B9A /* Frameworks */, 13B07F8E1A680F5B00A75B9A /* Resources */, 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, ); buildRules = ( ); dependencies = ( ); name = native; productName = "Hello World"; productReference = 13B07F961A680F5B00A75B9A /* native.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 83CBB9F71A601CBA00E9B192 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0610; ORGANIZATIONNAME = Facebook; TargetAttributes = { 00E356ED1AD99517003FC87E = { CreatedOnToolsVersion = 6.2; TestTargetID = 13B07F861A680F5B00A75B9A; }; 13B07F861A680F5B00A75B9A = { DevelopmentTeam = B6E32U87S9; }; }; }; buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "native" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 83CBB9F61A601CBA00E9B192; productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */; projectDirPath = ""; projectReferences = ( { ProductGroup = 00C302A81ABCB8CE00DB3ED1 /* Products */; ProjectRef = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */; }, { ProductGroup = 00C302B61ABCB90400DB3ED1 /* Products */; ProjectRef = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */; }, { ProductGroup = 00C302BC1ABCB91800DB3ED1 /* Products */; ProjectRef = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */; }, { ProductGroup = 78C398B11ACF4ADC00677621 /* Products */; ProjectRef = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */; }, { ProductGroup = 00C302D41ABCB9D200DB3ED1 /* Products */; ProjectRef = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */; }, { ProductGroup = 139105B71AF99BAD00B5F7CC /* Products */; ProjectRef = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */; }, { ProductGroup = 832341B11AAA6A8300B99B32 /* Products */; ProjectRef = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */; }, { ProductGroup = 00C302E01ABCB9EE00DB3ED1 /* Products */; ProjectRef = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */; }, { ProductGroup = 139FDEE71B06529A00C62182 /* Products */; ProjectRef = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */; }, { ProductGroup = 146834001AC3E56700842450 /* Products */; ProjectRef = 146833FF1AC3E56700842450 /* React.xcodeproj */; }, ); projectRoot = ""; targets = ( 13B07F861A680F5B00A75B9A /* native */, 00E356ED1AD99517003FC87E /* nativeTests */, ); }; /* End PBXProject section */ /* Begin PBXReferenceProxy section */ 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTActionSheet.a; remoteRef = 00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTGeolocation.a; remoteRef = 00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTImage.a; remoteRef = 00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTNetwork.a; remoteRef = 00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTVibration.a; remoteRef = 00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTSettings.a; remoteRef = 139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTWebSocket.a; remoteRef = 139FDEF31B06529B00C62182 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 146834041AC3E56700842450 /* libReact.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libReact.a; remoteRef = 146834031AC3E56700842450 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 78C398B91ACF4ADC00677621 /* libRCTLinking.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTLinking.a; remoteRef = 78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; 832341B51AAA6A8300B99B32 /* libRCTText.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = libRCTText.a; remoteRef = 832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ 00E356EC1AD99517003FC87E /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 13B07F8E1A680F5B00A75B9A /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */, 13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */, 84A404191C7EFBB100BCCEEA /* Default-568@2x.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Bundle React Native code and images"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "../node_modules/react-native/packager/react-native-xcode.sh"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 00E356EA1AD99517003FC87E /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 00E356F31AD99517003FC87E /* nativeTests.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 13B07F871A680F5B00A75B9A /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */, 13B07FC11A68108700A75B9A /* main.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 00E356F51AD99517003FC87E /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 13B07F861A680F5B00A75B9A /* native */; targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ 13B07FB11A68108700A75B9A /* LaunchScreen.xib */ = { isa = PBXVariantGroup; children = ( 13B07FB21A68108700A75B9A /* Base */, ); name = LaunchScreen.xib; path = native; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 00E356F61AD99517003FC87E /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; FRAMEWORK_SEARCH_PATHS = ( "$(SDKROOT)/Developer/Library/Frameworks", "$(inherited)", ); GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); INFOPLIST_FILE = nativeTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/native.app/native"; }; name = Debug; }; 00E356F71AD99517003FC87E /* Release */ = { isa = XCBuildConfiguration; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; COPY_PHASE_STRIP = NO; FRAMEWORK_SEARCH_PATHS = ( "$(SDKROOT)/Developer/Library/Frameworks", "$(inherited)", ); INFOPLIST_FILE = nativeTests/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 8.2; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/native.app/native"; }; name = Release; }; 13B07F941A680F5B00A75B9A /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; CODE_SIGN_IDENTITY = "iPhone Distribution: DuanYang Xue (B6E32U87S9)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEAD_CODE_STRIPPING = NO; HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); INFOPLIST_FILE = native/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 7.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; OTHER_LDFLAGS = "-ObjC"; PRODUCT_BUNDLE_IDENTIFIER = com.xueduanyang.reactnative; PRODUCT_NAME = native; PROVISIONING_PROFILE = ""; }; name = Debug; }; 13B07F951A680F5B00A75B9A /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; CODE_SIGN_IDENTITY = "iPhone Distribution: DuanYang Xue (B6E32U87S9)"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); INFOPLIST_FILE = native/Info.plist; IPHONEOS_DEPLOYMENT_TARGET = 7.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; ONLY_ACTIVE_ARCH = NO; OTHER_LDFLAGS = "-ObjC"; PRODUCT_BUNDLE_IDENTIFIER = com.xueduanyang.reactnative; PRODUCT_NAME = native; PROVISIONING_PROFILE = ""; }; name = Release; }; 83CBBA201A601CBA00E9B192 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); IPHONEOS_DEPLOYMENT_TARGET = 7.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; }; name = Debug; }; 83CBBA211A601CBA00E9B192 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, "$(SRCROOT)/../node_modules/react-native/React/**", ); IPHONEOS_DEPLOYMENT_TARGET = 7.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; VALIDATE_PRODUCT = YES; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "nativeTests" */ = { isa = XCConfigurationList; buildConfigurations = ( 00E356F61AD99517003FC87E /* Debug */, 00E356F71AD99517003FC87E /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "native" */ = { isa = XCConfigurationList; buildConfigurations = ( 13B07F941A680F5B00A75B9A /* Debug */, 13B07F951A680F5B00A75B9A /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "native" */ = { isa = XCConfigurationList; buildConfigurations = ( 83CBBA201A601CBA00E9B192 /* Debug */, 83CBBA211A601CBA00E9B192 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */; } ================================================ FILE: reactnative/ios/native.xcodeproj/xcshareddata/xcschemes/native.xcscheme ================================================ ================================================ FILE: reactnative/ios/nativeTests/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType BNDL CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1 ================================================ FILE: reactnative/ios/nativeTests/nativeTests.m ================================================ /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import #import #import "RCTLog.h" #import "RCTRootView.h" #define TIMEOUT_SECONDS 240 #define TEXT_TO_LOOK_FOR @"Welcome to React Native!" @interface nativeTests : XCTestCase @end @implementation nativeTests - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test { if (test(view)) { return YES; } for (UIView *subview in [view subviews]) { if ([self findSubviewInView:subview matching:test]) { return YES; } } return NO; } - (void)testRendersWelcomeScreen { UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; BOOL foundElement = NO; __block NSString *redboxError = nil; RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { if (level >= RCTLogLevelError) { redboxError = message; } }); while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { return YES; } return NO; }]; } RCTSetLogFunction(RCTDefaultLogFunction); XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); } @end ================================================ FILE: reactnative/package.json ================================================ { "name": "native", "version": "0.0.1", "private": true, "scripts": { "start": "react-native start" }, "dependencies": { "react-native": "^0.21.0" } } ================================================ FILE: reactnative/testFlex.js ================================================ (class Test extends App{ render() { return ( qwjel;qjw kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke ); } }).run(); ================================================ FILE: reactnative/testLineHeight.js ================================================ (class Test extends App{ render() { return ( 324234242342 ); } }).run(); ================================================ FILE: reactnative/testScroll.js ================================================ (class Test extends App{ render() { return ( kqwjelkqjwelkjqwlke kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd kqwjelkqjwelkjqwlke asdasdasdasdasdasdasd ); } }).run(); ================================================ FILE: reactnative/vsImgList.js ================================================ includeCSS("require('./css/vsImgList')"); class vsImgList extends Element { constructor(passedArgs){ super(); this.state = { list: null, pageHeight: windowHeight } this.passedArgs = { a: passedArgs.a, b: passedArgs.b, c: passedArgs.c } } componentWillMount(){ var self = this; fetch('http://statics1.jiaru.club/react-native-example/hesui.js', { method:'get', headers:{'Content-Type':'application/json;charset=utf-8'}, //body: [''].join('') } ).then(function(req){ req.json().then(function(res){ self.setState({ list: res.images }); }) }) } render() { return (
    { (()=>{ if(this.state.list){ return ( { this.state.list.map(function(o, idx){ return (
    ) }) }
    ); }else{ return (
    加载中...
    ); } }).call(this) }
    这是一个透明浮层的测试,上一页面传递过来的参数为{JSON.stringify(this.passedArgs)}
    ); } backBtn(){ pageRoute.pop(); } } module.exports = vsImgList; ================================================ FILE: reactnative/vsIndex.js ================================================ includeCSS("require('./css/vsIndex')"); class vsIndex extends Element { constructor(){ super(); this.state = { dataSource: SimpleListView.initDataSource(), } } render() { return (
    测试水平居中垂直居中
    ); } componentDidMount(){ var self = this; var url = 'http://statics1.jiaru.club/react-native-example/list.js'; console.debug(url) setTimeout(function(){ fetch(url, {method:'get',headers:{'Content-Type':'application/json;charset=utf-8', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding':'gzip, deflate, sdch', 'Accept-Language':'zh-CN,zh;q=0.8,en;q=0.6', 'Host':'statics1.jiaru.club' }, //body: [''].join('') } ).then(function(req){ req.json().then(function(res){ var l = res.list.slice(0); for(var i=0;i<2;i++){ l = l.concat(l) } var o = self.state.dataSource.cloneWithRows(l); self.setState({ dataSource: o }); }) }) // console.debug($('#HH')) setTimeout(function(){ $('#HH').animate({ from: { top: 0, left: 0, position: 'relative' }, to: { top: 0, left: 100 }, duration: 1000 }) },2000) }, 0); } _renderRow(row, sid, rowid){ return ; } } class Row extends Element{ constructor(){ super(); this.state = { numberOfLines: 3 } } render(){ try{ var row = this.props.data[0]; var rowid = this.props.data[2]; return (
    姓名: {row.name}
    简介: {row.desc}
    ); }catch(e){ console.debug(e); } } collapse(){ if(this.state.numberOfLines == 3){ this.setState({ numberOfLines: null }) }else{ this.setState({ numberOfLines: 3 }) } } jumpImgList(){ pageRoute.push({ page: require('./vsImgList'), a: 1, b: 2, c: 3 }) } } module.exports = vsIndex; ================================================ FILE: reactnative/webpack.config.js ================================================ var webpack = require('webpack'); module.exports = { entry : ['./index.ios2.js'], output : { filename : './z3.txt' }, module : { loaders: [{ test: /\.(js|jsx|es6)$/, exclude: /node_modules/, loader: 'babel-loader', query: { cacheDirectory: true, presets: ['stage-0', 'es2015', 'react'] } }], /* loaders : [ { loader : 'babel-loader', exclude : /node_modules/, query : { presets : [ 'es2015', 'react' ] } } ] */ }, plugins: [ new webpack.IgnorePlugin(/(^\w)|(\.\/rn\/\w+)/) ] } ================================================ FILE: web/common/html/A.js ================================================ class A extends Element { render() { return ; } } module.exports = A; ================================================ FILE: web/common/html/Button.js ================================================ class Button extends Element { render() { return : null } { this.props.rightButton ? : null } ); } } module.exports = NavBar; ================================================ FILE: web/common/html/Navigator.js ================================================ var Element = require('./Element'); class Navigator extends Element { constructor() { super(); window.pageRoute = window.pageRoute || new BrowserNav(); } componentDidMount() { pageRoute.setContainer(this.refs.J_navigator); pageRoute.push(this.props.initialRoute); pageRoute.route = this.props.initialRoute; } render() { return
    ; } } class BrowserNav { constructor(config) { this.indexs = []; this.route = {}; this.pageHistory = []; this.currentPageIndex = -1; } setContainer(container){ this.container = container; } push(route) { var page =React.createElement(route.page, { navigator: this }); var newPageContainer = document.createElement('div'); this.container.appendChild(newPageContainer); if(this.currentPageIndex >= 0){ this.pageHistory[this.currentPageIndex].container.style.display = 'none'; } this.pageHistory.push({ container: newPageContainer, page: page }); this.currentPageIndex = this.pageHistory.length - 1; React.render(page, newPageContainer); } pop() { if(this.pageHistory.length > 0){ var lastPageInfo = this.pageHistory.pop(); lastPageInfo.container.style.display = 'none'; this.currentPageIndex = this.pageHistory.length - 1; this.pageHistory[this.currentPageIndex].container.style.display = 'block'; //lastPageInfo.page.componentWillUnmount(); } } } module.exports = Navigator; ================================================ FILE: web/common/html/RightSliderMenu.js ================================================ class RightSliderMenu extends Element{ render(){ this.compatHTML(); return
    {this.props.children}
    ; } } module.exports = RightSliderMenu; ================================================ FILE: web/common/html/ScrollView/ScrollView.js ================================================ import ScrollResponder from '../ListView/ScrollResponder'; import View from '../View/View'; import throttle from 'domkit/throttle'; var SCROLLVIEW = 'ScrollView'; var INNERVIEW = 'InnerScrollView'; /** * Component that wraps platform ScrollView while providing * integration with touch locking "responder" system. * * Keep in mind that ScrollViews must have a bounded height in order to work, * since they contain unbounded-height children into a bounded container (via * a scroll interaction). In order to bound the height of a ScrollView, either * set the height of the view directly (discouraged) or make sure all parent * views have bounded height. Forgetting to transfer `{flex: 1}` down the * view stack can lead to errors here, which the element inspector makes * easy to debug. * * Doesn't yet support other contained responders from blocking this scroll * view from becoming the responder. */ var ScrollView = React.createClass({ propTypes: { /** * Controls whether iOS should automatically adjust the content inset * for scroll views that are placed behind a navigation bar or * tab bar/ toolbar. The default value is true. * @platform ios */ automaticallyAdjustContentInsets: React.PropTypes.bool, /** * The amount by which the scroll view content is inset from the edges * of the scroll view. Defaults to `{0, 0, 0, 0}`. * @platform ios */ // contentInset: EdgeInsetsPropType, /** * Used to manually set the starting scroll offset. * The default value is `{x: 0, y: 0}`. * @platform ios */ // contentOffset: PointPropType, /** * When true, the scroll view bounces when it reaches the end of the * content if the content is larger then the scroll view along the axis of * the scroll direction. When false, it disables all bouncing even if * the `alwaysBounce*` props are true. The default value is true. * @platform ios */ bounces: React.PropTypes.bool, /** * When true, gestures can drive zoom past min/max and the zoom will animate * to the min/max value at gesture end, otherwise the zoom will not exceed * the limits. * @platform ios */ bouncesZoom: React.PropTypes.bool, /** * When true, the scroll view bounces horizontally when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is true when `horizontal={true}` and false otherwise. * @platform ios */ alwaysBounceHorizontal: React.PropTypes.bool, /** * When true, the scroll view bounces vertically when it reaches the end * even if the content is smaller than the scroll view itself. The default * value is false when `horizontal={true}` and true otherwise. * @platform ios */ alwaysBounceVertical: React.PropTypes.bool, /** * When true, the scroll view automatically centers the content when the * content is smaller than the scroll view bounds; when the content is * larger than the scroll view, this property has no effect. The default * value is false. * @platform ios */ centerContent: React.PropTypes.bool, /** * These styles will be applied to the scroll view content container which * wraps all of the child views. Example: * * return ( * * * ); * ... * var styles = StyleSheet.create({ * contentContainer: { * paddingVertical: 20 * } * }); */ // contentContainerStyle: StyleSheetPropType(ViewStylePropTypes), /** * A floating-point number that determines how quickly the scroll view * decelerates after the user lifts their finger. Reasonable choices include * - Normal: 0.998 (the default) * - Fast: 0.9 * @platform ios */ decelerationRate: React.PropTypes.number, /** * When true, the scroll view's children are arranged horizontally in a row * instead of vertically in a column. The default value is false. */ horizontal: React.PropTypes.bool, /** * When true, the ScrollView will try to lock to only vertical or horizontal * scrolling while dragging. The default value is false. * @platform ios */ directionalLockEnabled: React.PropTypes.bool, /** * When false, once tracking starts, won't try to drag if the touch moves. * The default value is true. * @platform ios */ canCancelContentTouches: React.PropTypes.bool, /** * Determines whether the keyboard gets dismissed in response to a drag. * - 'none' (the default), drags do not dismiss the keyboard. * - 'on-drag', the keyboard is dismissed when a drag begins. * - 'interactive', the keyboard is dismissed interactively with the drag and moves in * synchrony with the touch; dragging upwards cancels the dismissal. * On android this is not supported and it will have the same behavior as 'none'. */ keyboardDismissMode: React.PropTypes.oneOf([ 'none', // default 'interactive', 'on-drag', ]), /** * When false, tapping outside of the focused text input when the keyboard * is up dismisses the keyboard. When true, the scroll view will not catch * taps, and the keyboard will not dismiss automatically. The default value * is false. */ keyboardShouldPersistTaps: React.PropTypes.bool, /** * The maximum allowed zoom scale. The default value is 1.0. * @platform ios */ maximumZoomScale: React.PropTypes.number, /** * The minimum allowed zoom scale. The default value is 1.0. * @platform ios */ minimumZoomScale: React.PropTypes.number, /** * Fires at most once per frame during scrolling. The frequency of the * events can be contolled using the `scrollEventThrottle` prop. */ onScroll: React.PropTypes.func, /** * Called when a scrolling animation ends. * @platform ios */ onScrollAnimationEnd: React.PropTypes.func, /** * When true, the scroll view stops on multiples of the scroll view's size * when scrolling. This can be used for horizontal pagination. The default * value is false. * @platform ios */ pagingEnabled: React.PropTypes.bool, /** * When false, the content does not scroll. * The default value is true. * @platform ios */ scrollEnabled: React.PropTypes.bool, /** * This controls how often the scroll event will be fired while scrolling * (in events per seconds). A higher number yields better accuracy for code * that is tracking the scroll position, but can lead to scroll performance * problems due to the volume of information being send over the bridge. * The default value is zero, which means the scroll event will be sent * only once each time the view is scrolled. * @platform ios */ scrollEventThrottle: React.PropTypes.number, /** * The amount by which the scroll view indicators are inset from the edges * of the scroll view. This should normally be set to the same value as * the `contentInset`. Defaults to `{0, 0, 0, 0}`. * @platform ios */ // scrollIndicatorInsets: EdgeInsetsPropType, /** * When true, the scroll view scrolls to top when the status bar is tapped. * The default value is true. * @platform ios */ scrollsToTop: React.PropTypes.bool, /** * When true, shows a horizontal scroll indicator. */ showsHorizontalScrollIndicator: React.PropTypes.bool, /** * When true, shows a vertical scroll indicator. */ showsVerticalScrollIndicator: React.PropTypes.bool, /** * An array of child indices determining which children get docked to the * top of the screen when scrolling. For example, passing * `stickyHeaderIndices={[0]}` will cause the first child to be fixed to the * top of the scroll view. This property is not supported in conjunction * with `horizontal={true}`. * @platform ios */ stickyHeaderIndices: React.PropTypes.arrayOf(React.PropTypes.number), // style: StyleSheetPropType(ViewStylePropTypes), /** * When set, causes the scroll view to stop at multiples of the value of * `snapToInterval`. This can be used for paginating through children * that have lengths smaller than the scroll view. Used in combination * with `snapToAlignment`. * @platform ios */ snapToInterval: React.PropTypes.number, /** * When `snapToInterval` is set, `snapToAlignment` will define the relationship * of the the snapping to the scroll view. * - `start` (the default) will align the snap at the left (horizontal) or top (vertical) * - `center` will align the snap in the center * - `end` will align the snap at the right (horizontal) or bottom (vertical) * @platform ios */ snapToAlignment: React.PropTypes.oneOf([ 'start', // default 'center', 'end', ]), /** * Experimental: When true, offscreen child views (whose `overflow` value is * `hidden`) are removed from their native backing superview when offscreen. * This can improve scrolling performance on long lists. The default value is * false. */ removeClippedSubviews: React.PropTypes.bool, /** * The current scale of the scroll view content. The default value is 1.0. * @platform ios */ zoomScale: React.PropTypes.number, }, mixins: [ScrollResponder.Mixin], getInitialState: function() { return this.scrollResponderMixinGetInitialState(); }, /** * Returns a reference to the underlying scroll responder, which supports * operations like `scrollTo`. All ScrollView-like components should * implement this method so that they can be composed while providing access * to the underlying scroll responder's methods. */ getScrollResponder: function(): ReactComponent { return this; }, getInnerViewNode: function(): any { return this.refs[INNERVIEW]; }, scrollTo: function(destY?: number, destX?: number) { // $FlowFixMe - Don't know how to pass Mixin correctly. Postpone for now // this.getScrollResponder().scrollResponderScrollTo(destX || 0, destY || 0); this.scrollWithoutAnimationTo(destY, destX); }, scrollWithoutAnimationTo: function(destY?: number, destX?: number) { // $FlowFixMe - Don't know how to pass Mixin correctly. Postpone for now // this.getScrollResponder().scrollResponderScrollWithouthAnimationTo( // destX || 0, // destY || 0, // ); var scrollView = React.findDOMNode(this.refs[SCROLLVIEW]); scrollView.scrollTop = destY || 0; scrollView.scrollLeft = destX || 0; }, handleScroll: function(e: Event) { // if (__DEV__) { // if (this.props.onScroll && !this.props.scrollEventThrottle) { // console.log( // 'You specified `onScroll` on a but not ' + // '`scrollEventThrottle`. You will only receive one event. ' + // 'Using `16` you get all the events but be aware that it may ' + // 'cause frame drops, use a bigger number if you don\'t need as ' + // 'much precision.' // ); // } // } // if (Platform.OS === 'android') { // if (this.props.keyboardDismissMode === 'on-drag') { // dismissKeyboard(); // } // } this.props.onScroll && this.props.onScroll(e); }, render: function() { var contentContainerStyle = [ styles.contentContainer, this.props.horizontal && styles.contentContainerHorizontal, this.props.contentContainerStyle, ]; // if (__DEV__ && this.props.style) { // var style = flattenStyle(this.props.style); // var childLayoutProps = ['alignItems', 'justifyContent'] // .filter((prop) => style && style[prop] !== undefined); // invariant( // childLayoutProps.length === 0, // 'ScrollView child layout (' + JSON.stringify(childLayoutProps) + // ') must by applied through the contentContainerStyle prop.' // ); // } var contentContainer = {this.props.children} ; var alwaysBounceHorizontal = this.props.alwaysBounceHorizontal !== undefined ? this.props.alwaysBounceHorizontal : this.props.horizontal; var alwaysBounceVertical = this.props.alwaysBounceVertical !== undefined ? this.props.alwaysBounceVertical : !this.props.horizontal; if (this.props.scrollEventThrottle && this.props.onScroll) { var handleScroll = throttle(this.handleScroll, this.props.scrollEventThrottle); } var props = { ...this.props, alwaysBounceHorizontal, alwaysBounceVertical, style: ([styles.base, this.props.style]: ?Array), onTouchStart: this.scrollResponderHandleTouchStart, onTouchMove: this.scrollResponderHandleTouchMove, onTouchEnd: this.scrollResponderHandleTouchEnd, onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag, onScrollEndDrag: this.scrollResponderHandleScrollEndDrag, onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin, onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd, onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder, onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture, // onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder, // onScroll: handleScroll, onScrollShouldSetResponder: handleScroll, // replace onScroll in the props onScroll: function() {}, onResponderGrant: this.scrollResponderHandleResponderGrant, onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest, onResponderTerminate: this.scrollResponderHandleTerminate, onResponderRelease: this.scrollResponderHandleResponderRelease, onResponderReject: this.scrollResponderHandleResponderReject, }; return ( {contentContainer} ); } }); var styles = { base: { overflow: 'scroll', WebkitOverflowScrolling: 'touch', flex: 1, }, contentContainer: { position: 'absolute', minWidth: '100%', }, contentContainerHorizontal: { alignSelf: 'flex-start', flexDirection: 'row', }, }; module.exports = ScrollView; ================================================ FILE: web/common/html/ScrollView.js ================================================ class ScrollView extends Element{ render(){ this.compatHTML(); return
    {this.props.children}
    ; } } module.exports = ScrollView; ================================================ FILE: web/common/html/SimpleListView.js ================================================ class SimpleListView extends Element { render() { this.compatHTML(); return ; } } SimpleListView.initDataSource = () => { var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); var defaultDS = ds.cloneWithRows([]); return defaultDS; } module.exports = SimpleListView; ================================================ FILE: web/common/html/Span.js ================================================ var Element = require('./Element'); class Span extends Element { render() { this.compatHTML(); return ; } } module.exports = Span; ================================================ FILE: web/common/html/TabSlider.js ================================================ class TabSlider extends Element{ render(){ this.compatHTML(); return (
    按起降地
    按航班号
    我的关注
    ); } selected(idx){ this.props.config.onChange(idx); } } module.exports = TabSlider; ================================================ FILE: web/common/html/Utilties/ErrorUitls.js ================================================ /* eslint global-strict:0 */ (function(global) { var ErrorUtils = { _inGuard: 0, _globalHandler: null, setGlobalHandler: function(fun) { ErrorUtils._globalHandler = fun; }, reportError: function(error) { ErrorUtils._globalHandler && ErrorUtils._globalHandler(error); }, reportFatalError: function(error) { ErrorUtils._globalHandler && ErrorUtils._globalHandler(error, true); }, applyWithGuard: function(fun, context, args) { try { ErrorUtils._inGuard++; return fun.apply(context, args); } catch (e) { ErrorUtils.reportError(e); } finally { ErrorUtils._inGuard--; } }, applyWithGuardIfNeeded: function(fun, context, args) { if (ErrorUtils.inGuard()) { return fun.apply(context, args); } else { ErrorUtils.applyWithGuard(fun, context, args); } }, inGuard: function() { return ErrorUtils._inGuard; }, guard: function(fun, name, context) { if (typeof fun !== 'function') { console.warn('A function must be passed to ErrorUtils.guard, got ', fun); return null; } name = name || fun.name || ''; function guarded() { return ( ErrorUtils.applyWithGuard( fun, context || this, arguments, null, name ) ); } return guarded; } }; global.ErrorUtils = ErrorUtils; /** * This is the error handler that is called when we encounter an exception * when loading a module. */ function setupErrorGuard() { var onError = function(e) { global.console.error( 'Error: ' + '\n stack: ' + e.stack + '\n line: ' + e.line + '\n message: ' + e.message, e ); }; global.ErrorUtils.setGlobalHandler(onError); } setupErrorGuard(); })(window); module.exports = ErrorUtils; ================================================ FILE: web/common/html/Utilties/LayoutMixin.js ================================================ import getLayout from './getLayout'; var LayoutMixin = { getInitialState: function() { return {layout: {}}; }, componentDidMount: function() { this.layoutHandle(); }, componentDidUpdate: function() { this.layoutHandle(); }, layoutHandle: function() { if (this.props.onLayout) { var layout = getLayout(React.findDOMNode(this)); var stateLayout = this.state.layout; if (stateLayout.x !== layout.x || stateLayout.y !== layout.y || stateLayout.width !== layout.width || stateLayout.height !== layout.height) { this.props.onLayout({nativeEvent: {layout}}); this.setState({layout}); } } } }; module.exports = { Mixin: LayoutMixin }; ================================================ FILE: web/common/html/Utilties/dismissKeyboard.js ================================================ function dismissKeyboard() { document.activeElement.blur(); } module.exports = dismissKeyboard; ================================================ FILE: web/common/html/Utilties/getLayout.js ================================================ // get element x, y function getCumulativeOffset(obj) { var left, top; left = top = 0; if (obj.offsetParent) { do { left += obj.offsetLeft; top += obj.offsetTop; } while (obj = obj.offsetParent); } return { x : left, y : top }; } // this functions returns the x, y, width and height of a given dom node function getLayout(element) { var rect = getCumulativeOffset(element); return { x: rect.x, y: rect.y, width: element.offsetWidth, height: element.offsetHeight }; } module.exports = getLayout; ================================================ FILE: web/common/html/Utilties/setNativeProps.js ================================================ function convertTransform(style) { var result = {}; var transform = ''; for (var k in style) { if (k === 'transformMatrix') { transform += ( 'matrix3d(' + style[k].join(',') + ') ' ); }else if ( k === 'translateX' || k === 'translateY' || k === 'translateZ') { var v = style[k]; if (typeof(v) === 'number') v += 'px'; transform += ( k + '(' + v + ') ' ); } else if (k === 'scaleX' || k === 'scaleY' || k === 'scaleZ') { transform += ( k + '(' + style[k] + ') '); } else { var val = style[k]; if (typeof val == 'number') { val += 'px'; } result[k] = val; } } if (transform) { result.transform = transform; } return result; } function setNativeProps(ref, props) { var node = React.findDOMNode(ref); var style = props.style; if (style) { style = convertTransform(style); for (var k in style) { node.style[k] = style[k]; } } } module.exports = setNativeProps; ================================================ FILE: web/common/html/View/View.js ================================================ import { Mixin as LayoutMixin } from '../Utilties/LayoutMixin'; var View = React.createClass({ mixins: [LayoutMixin], propTypes: { /** * Used to locate this view in end-to-end tests. NB: disables the 'layout-only * view removal' optimization for this view! */ testID: React.PropTypes.string, /** * For most touch interactions, you'll simply want to wrap your component in * `TouchableHighlight` or `TouchableOpacity`. Check out `Touchable.js`, * `ScrollResponder.js` and `ResponderEventPlugin.js` for more discussion. */ onMoveShouldSetResponder: React.PropTypes.func, onResponderGrant: React.PropTypes.func, onResponderMove: React.PropTypes.func, onResponderReject: React.PropTypes.func, onResponderRelease: React.PropTypes.func, onResponderTerminate: React.PropTypes.func, onResponderTerminationRequest: React.PropTypes.func, onStartShouldSetResponder: React.PropTypes.func, onStartShouldSetResponderCapture: React.PropTypes.func, /** * Invoked on mount and layout changes with * * {nativeEvent: { layout: {x, y, width, height}}}. * * This event is fired immediately once the layout has been calculated, but * the new layout may not yet be reflected on the screen at the time the * event is received, especially if a layout animation is in progress. */ onLayout: React.PropTypes.func, /** * In the absence of `auto` property, `none` is much like `CSS`'s `none` * value. `box-none` is as if you had applied the `CSS` class: * * ``` * .box-none { * pointer-events: none; * } * .box-none * { * pointer-events: all; * } * ``` * * `box-only` is the equivalent of * * ``` * .box-only { * pointer-events: all; * } * .box-only * { * pointer-events: none; * } * ``` * * But since `pointerEvents` does not affect layout/appearance, and we are * already deviating from the spec by adding additional modes, we opt to not * include `pointerEvents` on `style`. On some platforms, we would need to * implement it as a `className` anyways. Using `style` or not is an * implementation detail of the platform. */ pointerEvents: React.PropTypes.oneOf([ 'box-none', 'none', 'box-only', 'auto', ]), style: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.array ]), }, render: function() { return (
    {this.props.children}
    ); } }); module.exports = View; ================================================ FILE: web/common/react.js ================================================ /** * React v0.14.3 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.React = f()}})(function(){var define,module,exports;return (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 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; },{"130":130,"148":148,"15":15,"19":19,"20":20,"90":90,"94":94}],4:[function(_dereq_,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; },{}],5:[function(_dereq_,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 CSSPropertyOperations * @typechecks static-only */ 'use strict'; var CSSProperty = _dereq_(4); var ExecutionEnvironment = _dereq_(130); var ReactPerf = _dereq_(71); var camelizeStyleName = _dereq_(132); var dangerousStyleValue = _dereq_(105); var hyphenateStyleName = _dereq_(143); var memoizeStringOnly = _dereq_(150); var warning = _dereq_(155); 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 ("development" !== '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; "development" !== '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; "development" !== '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; "development" !== '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 ("development" !== '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 ("development" !== '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; },{"105":105,"130":130,"132":132,"143":143,"150":150,"155":155,"4":4,"71":71}],6:[function(_dereq_,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 CallbackQueue */ 'use strict'; var PooledClass = _dereq_(24); var assign = _dereq_(23); var invariant = _dereq_(144); /** * 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) ? "development" !== '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; },{"144":144,"23":23,"24":24}],7:[function(_dereq_,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 = _dereq_(15); var EventPluginHub = _dereq_(16); var EventPropagators = _dereq_(19); var ExecutionEnvironment = _dereq_(130); var ReactUpdates = _dereq_(83); var SyntheticEvent = _dereq_(92); var getEventTarget = _dereq_(114); var isEventSupported = _dereq_(119); var isTextInputElement = _dereq_(120); var keyOf = _dereq_(148); 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; },{"114":114,"119":119,"120":120,"130":130,"148":148,"15":15,"16":16,"19":19,"83":83,"92":92}],8:[function(_dereq_,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ClientReactRootIndex * @typechecks */ 'use strict'; var nextReactRootIndex = 0; var ClientReactRootIndex = { createReactRootIndex: function () { return nextReactRootIndex++; } }; module.exports = ClientReactRootIndex; },{}],9:[function(_dereq_,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 DOMChildrenOperations * @typechecks static-only */ 'use strict'; var Danger = _dereq_(12); var ReactMultiChildUpdateTypes = _dereq_(67); var ReactPerf = _dereq_(71); var setInnerHTML = _dereq_(124); var setTextContent = _dereq_(125); var invariant = _dereq_(144); /** * 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} updates List of update configurations. * @param {array} 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 ? "development" !== '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 when using tables, ' + 'nesting tags like ,

    , or , or using non-SVG elements ' + 'in an 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; },{"12":12,"124":124,"125":125,"144":144,"67":67,"71":71}],10:[function(_dereq_,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 DOMProperty * @typechecks static-only */ 'use strict'; var invariant = _dereq_(144); 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) ? "development" !== '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) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined; !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? "development" !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? "development" !== '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 ("development" !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if ("development" !== '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 ` in `.) * 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: "development" !== '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; },{"144":144}],11:[function(_dereq_,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 DOMPropertyOperations * @typechecks static-only */ 'use strict'; var DOMProperty = _dereq_(10); var ReactPerf = _dereq_(71); var quoteAttributeValueForBrowser = _dereq_(122); var warning = _dereq_(155); // 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; "development" !== '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 ("development" !== '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. "development" !== '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 ("development" !== '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 ("development" !== '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 ("development" !== 'production') { warnUnknownProperty(name); } } }; ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', { setValueForProperty: 'setValueForProperty', setValueForAttribute: 'setValueForAttribute', deleteValueForProperty: 'deleteValueForProperty' }); module.exports = DOMPropertyOperations; },{"10":10,"122":122,"155":155,"71":71}],12:[function(_dereq_,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 Danger * @typechecks static-only */ 'use strict'; var ExecutionEnvironment = _dereq_(130); var createNodesFromMarkup = _dereq_(135); var emptyFunction = _dereq_(136); var getMarkupWrap = _dereq_(140); var invariant = _dereq_(144); 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} markupList List of markup strings to render. * @return {array} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function (markupList) { !ExecutionEnvironment.canUseDOM ? "development" !== '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] ? "development" !== '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

    ; * } * }); * * 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
    Hello, {name}!
    ; * } * * @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 ("development" !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if ("development" !== '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 ("development" !== '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__ "development" !== '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) ? "development" !== '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) ? "development" !== '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') ? "development" !== '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) ? "development" !== '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)) ? "development" !== '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 ("development" !== '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 ? "development" !== '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 ? "development" !== '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') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? "development" !== '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 ("development" !== '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) { "development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined; } else if (!args.length) { "development" !== '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 ("development" !== '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 ("development" !== '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 ("development" !== 'production') { "development" !== '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 ("development" !== '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)) ? "development" !== '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 ("development" !== '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 ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined; if ("development" !== 'production') { "development" !== '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; "development" !== '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; },{"137":137,"144":144,"147":147,"148":148,"155":155,"23":23,"30":30,"52":52,"69":69,"72":72,"73":73}],30:[function(_dereq_,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 ReactComponent */ 'use strict'; var ReactNoopUpdateQueue = _dereq_(69); var canDefineProperty = _dereq_(104); var emptyObject = _dereq_(137); var invariant = _dereq_(144); var warning = _dereq_(155); /** * 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) ? "development" !== '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 ("development" !== 'production') { "development" !== '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 ("development" !== '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 () { "development" !== '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; },{"104":104,"137":137,"144":144,"155":155,"69":69}],31:[function(_dereq_,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 = _dereq_(40); var ReactMount = _dereq_(65); /** * 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; },{"40":40,"65":65}],32:[function(_dereq_,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 ReactComponentEnvironment */ 'use strict'; var invariant = _dereq_(144); 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 ? "development" !== '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; },{"144":144}],33:[function(_dereq_,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 ReactCompositeComponent */ 'use strict'; var ReactComponentEnvironment = _dereq_(32); var ReactCurrentOwner = _dereq_(34); var ReactElement = _dereq_(52); var ReactInstanceMap = _dereq_(62); var ReactPerf = _dereq_(71); var ReactPropTypeLocations = _dereq_(73); var ReactPropTypeLocationNames = _dereq_(72); var ReactReconciler = _dereq_(76); var ReactUpdateQueue = _dereq_(82); var assign = _dereq_(23); var emptyObject = _dereq_(137); var invariant = _dereq_(144); var shouldUpdateReactComponent = _dereq_(126); var warning = _dereq_(155); 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 ("development" !== '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 ("development" !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { "development" !== '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 "development" !== '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 ("development" !== '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. "development" !== '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; "development" !== '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; "development" !== '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; "development" !== '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; "development" !== '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; "development" !== '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; "development" !== '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)) ? "development" !== '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 ("development" !== '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') ? "development" !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined; if ("development" !== 'production') { this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? "development" !== '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 ("development" !== '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') ? "development" !== '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 "development" !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined; } else { "development" !== '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 ("development" !== 'production') { "development" !== '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 ("development" !== '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)) ? "development" !== '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) ? "development" !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined; var publicComponentInstance = component.getPublicInstance(); if ("development" !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; "development" !== '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; },{"126":126,"137":137,"144":144,"155":155,"23":23,"32":32,"34":34,"52":52,"62":62,"71":71,"72":72,"73":73,"76":76,"82":82}],34:[function(_dereq_,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; },{}],35:[function(_dereq_,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 ReactDOM */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactCurrentOwner = _dereq_(34); var ReactDOMTextComponent = _dereq_(46); var ReactDefaultInjection = _dereq_(49); var ReactInstanceHandles = _dereq_(61); var ReactMount = _dereq_(65); var ReactPerf = _dereq_(71); var ReactReconciler = _dereq_(76); var ReactUpdates = _dereq_(83); var ReactVersion = _dereq_(84); var findDOMNode = _dereq_(108); var renderSubtreeIntoContainer = _dereq_(123); var warning = _dereq_(155); 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 ("development" !== 'production') { var ExecutionEnvironment = _dereq_(130); 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; "development" !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '') : 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; },{"108":108,"123":123,"130":130,"155":155,"34":34,"46":46,"49":49,"61":61,"65":65,"71":71,"76":76,"83":83,"84":84}],36:[function(_dereq_,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