<commit_before>/* Flow v0.X + genData v1.1 | github.com/bemson | (c) 2011, MIT */
function genData(a){var b=arguments,c=b.callee,d,e,f,g,h,i=[],j=[],k={},l,m,n,o=c,p;if(!(this instanceof c)){b[1]&&(i=typeof b[1]=="function"?[b[1]]:b[1]),f=i.length,b[2]&&(o=b[2]);function q(a,b){this.name=a,this.value=b}q.prototype=o.prototype,q.prototype.constructor=o,l=[["",a]];while(l.length){n=l.shift(),p=new q(n[0],n[1]),e=0,d={parent:0,omit:0,scan:1,exit:0},b=[p.name,p.value,n[2],j,d,k];while(e<f&&!d.exit)i[e++].apply(p,b);d.omit?p._OMIT=!0:j.push(p);if(d.exit)l=[];else{m=[];if(d.scan&&typeof p.value=="object"){h=d.parent&&(d.parent instanceof o||d.parent instanceof c)?d.parent:p;for(g in p.value)p.value.hasOwnProperty(g)&&m.push([g,p.value[g],h])}l=m.concat(l)}}return j}if(a){~{}.toString.call(b[1]).indexOf("y")&&(o=a,b=b[1]),i=i.concat([].slice.call(b));function r(a,b,d){var e=~{}.toString.call(b).indexOf("y");if(!(this instanceof r))return c(a,i.concat(b||[]),d?d:r);if(a)return new c(e?a:r,i.concat(e?b:[].slice.call(arguments)));return this}r.prototype=new o,r.prototype.constructor=o;return r}return this}
!function(a,b,c,d){function m(){}function n(){}function o(a){function b(b){var c=b&&b.toString(f);return typeof c=="object"&&(c.pkgs.filter(function(b){return b.name===a})[0]||{}).pkg||!1}function c(){}function d(){}return b.prototype=new n,b.init=b.dataKey=b.invalidKey=b.onBegin=b.onEnd=b.onTraverse=0,c.prototype=new m,m=c,b.proxy=c.prototype,b.state=d.prototype,h[a]=g.push({name:a,pkg:b,model:c,state:d})-1,b}function p(a){var b=j(a);return b[0].parentIndex=b[0].childIndex=0,b.unshift(j()[0]),b[0].children.push(1),b[0].name="_flow",b[0].index=0,b[0].depth=0,b[0].path="..//",b[0].firstChildIndex=b[0].lastChildIndex=1,b}function q(a,b,c){var d=this;typeof c!="object"&&(c={}),d.prgm=a,d.states=p(a),d.shared={id:++e,currentIndex:0,targetIndex:-1,go:function(a){var b=d.states[a];return b&&(d.target=b,d.shared.targetIndex=b.index),d.stop=0,d.go()},stop:function(){return d.stop=1,d.loop},post:function(a){switch(typeof a){case"function":return d.posts.push(a)-1;case"number":if(d.posts[a])return d.posts[a]=null,!0}return!1}},d.posts=[],d.current=d.states[0],d.target=d.loop=0,d.pkgs=g.map(function(a){function f(){}var e={name:a.name};return f.prototype=new a.pkg,e.pkg=new f,e.pkg.states=k(d.states,[],a.state),typeof a.pkg.init=="function"&&a.pkg.init.call(e.pkg,c),e.pkg.tank=d.shared,e.pkg.proxy=b,e})}function r(a,b){function h(a){return a===f?e:Object.prototype.toString.apply(this,arguments)}function i(){function a(){this.pkgs=c,this.toString=h}return a.prototype=new m,a}if(this instanceof arguments.callee){var c={},d=new(i()),e=new q(a instanceof m?a.toString(f).prgm:a,d,typeof b=="object"?b:{});return g.forEach(function(a){var b=i();b.prototype=new a.model,c[a.name]=new b}),d}throw new Error('Requires "new"')}var e=0,f={},g=[],h={},i=function(a,b,c){return b.length&&g.some(function(d){var e=d.pkg[a];switch(typeof e){case"function":return e(b,c);case"object":if(e instanceof RegExp)return e.test(b)}return!1})},j=new c(function(a,b,c,e,f){var g=this,h=i("invalidKey",a,b),j=i("dataKey",a,b);h||j?(f.omit=1,f.scan=0,j&&!h&&(c.data[a]=b)):(g.inContext=g.parentIndex=g.previousIndex=g.nextIndex=g.firstChildIndex=d,g.index=e.length+1,g.depth=c?c.depth+1:1,g.name=c?a:"_root",g.data={},g.path=c?c.path+a+"/":"//",g.children=[],c&&(g.parentIndex=c.index,c.children.length||(c.firstChildIndex=g.index),g.childIndex=c.children.push(g.index)-1,c.lastChildIndex=g.index,g.childIndex&&(g.previousIndex=c.children[g.childIndex-1],e[g.previousIndex-1].nextIndex=g.index)))}),k=new c(function(a,b,c,d,e){var f=this,g;if(!c)e.omit=1;else{e.scan=0;for(g in b)b.hasOwnProperty(g)&&g!=="inContext"&&(f[g]=b[g])}}),l=b.prototype;l.some||(l.some=function(a,b){for(var c=0,d=this.length;c<d;c++)if(a.call(b,this[c],c,this))return!0;return!1}),l.filter||(l.filter=function(a,b){var c=[],d=0,e=this.length,f;for(;d<e;d++)f=this[d],a.call(b,f,d,this)&&c.push(f);return c}),l.forEach||(l.forEach=function(a,b){for(var c=0,d=this.length;c<d;c++)a.call(b,this[c],c,this)}),l.map||(l.map=function(a,c){var d=0,e=this.length,f=new b(e);for(;d<e;d++)f[d]=a.call(c,this[d],d,this);return f}),m.prototype.constructor=r,n.prototype.inState=function(a){return a<this.states.length?!0:!1},q.prototype={go:function(){var a=this,b=a.states,c=a.shared,d,e=0,f=a.current,g=0,h=0,i;if(a.loop)return!!a.target;a.posts=[],a.loop=1,a.fire("Begin");while(a.loop)a.target&&!a.stop?(i=0,d=a.target.index-f.index,d?d>0&&f.index<2||!a.target.path.indexOf(f.path)?f.inContext?(g=0,h=f.firstChildIndex):(g=1,h=1,f.inContext=1):f.inContext?(g=1,h=2,f.inContext=0):(a.target.path.indexOf(b[f.parentIndex].path)&&(d=-1),h=d<0?4:3,f.lastEvent===2||f.lastEvent===h||f.lastEvent+h===7?(g=0,h=d>0?f.nextIndex:f.previousIndex||f.parentIndex):g=1):(g=1,h=f.inContext?0:1,f.inContext&&(a.target=0,c.targetIndex=-1),f.inContext=1),g?(f.lastEvent=h,e++,a.fire("Traverse",[h])):(f.lastEvent=0,f=a.current=b[h],c.currentIndex=h)):!i&&(a.stop||!a.target)?(i=1,a.fire("End")):a.loop=0;return a.posts.forEach(function(a){typeof a=="function"&&a()}),e},fire:function(a,b){b=b||[],b.unshift(a.toLowerCase()),a="on"+a,this.pkgs.forEach(function(c){var d=g[h[c.name]].pkg[a];typeof d=="function"&&d.apply(c.pkg,b)})}},r.pkg=function(a){return arguments.length?typeof a=="string"&&/\w/.test(a)?(h.hasOwnProperty(a)||o(a),g[h[a]].pkg):!1:g.map(function(a){return a.name})},a.Flow=r}(this,Array,genData);<commit_msg>Minified for testing (6K/2.4K)<commit_after>/* Flow v1.0.0 + genData v1.2.0 | github.com/bemson | (c) 2011, MIT */
function genData(a){var b=arguments,c=b.callee,d,e,f,g,h=[],i=[],j,k={},l,m,n,o=c,p=typeof o=="function",q;if(this instanceof c){if(a){~{}.toString.call(b[1]).indexOf("y")&&(o=a,b=b[1]),h=h.concat([].slice.call(b));function s(a,b,d){var e=~{}.toString.call(b).indexOf("y");return this instanceof s?a?new c(e?a:s,h.concat(e?b:[].slice.call(arguments))):this:c(a,h.concat(b||[]),d?d:s)}return s.prototype=p?new o:o,s}return this}b[1]&&(h=typeof b[1]=="function"?[b[1]]:b[1]),f=h.length,b[2]&&(o=b[2]);function r(a,b){this.name=a,this.value=b}r.prototype=p?o.prototype:o,l=[["",a]];while(l.length){n=l.shift(),q=new r(n[0],n[1]),e=0,d={parent:0,omit:0,scan:1,exit:0},b=[q.name,q.value,n[2],i,d,k];while(e<f&&!d.exit)h[e++].apply(q,b);d.omit?q._OMIT=!0:i.push(q);if(d.exit)l=[];else{m=[];if(d.scan&&typeof q.value=="object"){j=typeof d.parent=="object"?d.parent:q;for(g in q.value)q.value.hasOwnProperty(g)&&m.push([g,q.value[g],j])}l=m.concat(l)}}return i};
!function(inCommonJsEnv,Array,Object,window,undefined){function ProxyModel(){}function pkgModel(){}function definePackage(a){function c(a){var c=a&&a.toString(secretObject);return c instanceof Flow&&(c.pkgs[b]||{}).pkg||!1}function d(){}function e(){}var b=pkgDefs.length;return c.prototype=new pkgModel,c.init=c.attributeKey=c.invalidKey=c.onBegin=c.onEnd=c.onTraverse=0,d.prototype=new ProxyModel,ProxyModel=d,c.proxy=d.prototype,c.state=e.prototype,pkgsIdx[a]=pkgDefs.push({name:a,pkg:c,model:d,state:e})-1,c}function createProgramStates(program){var states=genStates(program);states[0].parentIndex=states[0].childIndex=0,states.unshift(genStates()[0]);with(states[0])children.push(1),name="_flow",index=0,depth=0,path="..//";return states[0].firstChildIndex=states[0].lastChildIndex=1,states}function Flow(a,b,c){var d=this;d.prgm=a,d.states=createProgramStates(a),d.tank={id:++flowCnt,currentIndex:0,targetIndex:-1,stop:function(){return d.stop=1,d.loop},post:function(a){switch(typeof a){case"function":return d.posts.push(a)-1;case"number":if(d.posts[a])return d.posts[a]=0,!0}return!1}},d.posts=[],d.current=d.states[0],d.target=d.loop=0,d.pkgs=pkgDefs.map(function(a){function f(){}var e={name:a.name};return f.prototype=new a.pkg,e.pkg=new f,e.pkg.states=genCloneStates(d.states,0,a.state),e.pkg.tank=d.tank,e.pkg.proxy=b,typeof a.pkg.init=="function"&&a.pkg.init.call(e.pkg,c),e}),d.tank.go=function(a){var b=d.states[a];return b&&(d.target=b,d.tank.targetIndex=b.index),d.stop=0,d.go()}}function FlowAPI(a,b){function f(a){return a===secretObject?e:Object.prototype.toString.apply(this,arguments)}function g(){function a(){this.pkgs=c,this.toString=f}return a.prototype=new ProxyModel,a}if(this instanceof arguments.callee){var c={},d=new(g()),e=new Flow(a instanceof ProxyModel?a.toString(secretObject).prgm:a instanceof pkgModel?a.proxy.toString(secretObject).prgm:a,d,b instanceof Object?b:{});return pkgDefs.forEach(function(a){var b=g();b.prototype=new a.model,c[a.name]=new b}),d}throw new Error('Missing "new" operator.')}if(!inCommonJsEnv&&window.Flow)return;var environment=inCommonJsEnv?exports:window,genData=(inCommonJsEnv?require("genData"):window).genData,flowCnt=0,secretObject={},pkgDefs=[],pkgsIdx={},testStateKey=function(a,b,c){return b.length&&pkgDefs.some(function(d){var e=d.pkg[a];switch(typeof e){case"function":return e(b,c);case"object":if(e instanceof RegExp)return e.test(b)}})},genStates=new genData(function(a,b,c,d,e){var f=this,g=testStateKey("invalidKey",a,b),h=testStateKey("attributeKey",a,b);g||h?(e.omit=1,e.scan=0,h&&!g&&(c.attributes[a]=b)):(f.inContext=f.parentIndex=f.previousIndex=f.nextIndex=f.firstChildIndex=undefined,f.index=d.length+1,f.depth=c?c.depth+1:1,f.name=c?a:"_root",f.attributes={},f.path=c?c.path+a+"/":"//",f.children=[],c&&(f.parentIndex=c.index,c.children.length||(c.firstChildIndex=f.index),f.childIndex=c.children.push(f.index)-1,c.lastChildIndex=f.index,f.childIndex&&(f.previousIndex=c.children[f.childIndex-1],d[f.previousIndex-1].nextIndex=f.index)))}),genCloneStates=new genData(function(a,b,c,d,e){if(!c)e.omit=1;else{e.scan=0;for(var f in b)b.hasOwnProperty(f)&&(this[f]=b[f])}}),arrayPrototype=Array.prototype;arrayPrototype.some||(arrayPrototype.some=function(a,b){for(var c=0,d=this.length;c<d;c++)if(a.call(b,this[c],c,this))return!0;return!1}),arrayPrototype.filter||(arrayPrototype.filter=function(a,b){var c=[],d=0,e=this.length,f;for(;d<e;d++)f=this[d],a.call(b,f,d,this)&&c.push(f);return c}),arrayPrototype.forEach||(arrayPrototype.forEach=function(a,b){for(var c=0,d=this.length;c<d;c++)a.call(b,this[c],c,this)}),arrayPrototype.map||(arrayPrototype.map=function(a,b){var c=0,d=this.length,e=new Array(d);for(;c<d;c++)e[c]=a.call(b,this[c],c,this);return e}),ProxyModel.prototype.constructor=FlowAPI,Flow.prototype={go:function(){var a=this,b=a.states,c=a.tank,d,e=0,f=a.current,g=0,h=0,i;if(a.loop)return!!a.target;a.posts=[],a.loop=1,a.fire("Begin");while(a.loop)a.target&&!a.stop?(i=0,d=a.target.index-f.index,d?d>0&&f.index<2||!a.target.path.indexOf(f.path)?f.inContext?(g=0,h=f.firstChildIndex):(g=1,h=1,f.inContext=1):f.inContext?(g=1,h=2,f.inContext=0):(a.target.path.indexOf(b[f.parentIndex].path)&&(d=-1),h=d<0?4:3,f.lastEvent===2||f.lastEvent===h||f.lastEvent+h===7?(g=0,h=d>0?f.nextIndex:f.previousIndex||f.parentIndex):g=1):(g=1,h=f.inContext?0:1,f.inContext&&(a.target=0,c.targetIndex=-1),f.inContext=1),g?(f.lastEvent=h,e++,a.fire("Traverse",[h])):(f.lastEvent=0,f=a.current=b[h],c.currentIndex=h)):!i&&(a.stop||!a.target)?(i=1,a.fire("End")):a.loop=0;return a.posts.forEach(function(a){typeof a=="function"&&a()}),e},fire:function(a,b){b=b||[],b.unshift(a.toLowerCase()),a="on"+a,this.pkgs.forEach(function(c){var d=pkgDefs[pkgsIdx[c.name]].pkg[a];typeof d=="function"&&d.apply(c.pkg,b)})}},FlowAPI.pkg=function(a){return arguments.length?typeof a=="string"&&/\w/.test(a)?(pkgsIdx.hasOwnProperty(a)||definePackage(a),pkgDefs[pkgsIdx[a]].pkg):!1:pkgDefs.map(function(a){return a.name})},environment.Flow=FlowAPI}(typeof require!="undefined",Array,Object,this);<|endoftext|>


<commit_before>'use strict';

import React, {Component} from 'react';
import {
  AppRegistry,
  Navigator,
  Text,
  View,
  TouchableHighlight,
  StyleSheet,
  AsyncStorage
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import PasscodeAuth from 'react-native-passcode-auth';

import OriginalScene from './js/page/OriginalScene';
import NewScene from './js/page/NewScene';
import TimelineScene from './js/page/TimelineScene';
import SitesScene from './js/page/SitesScene';
import SettingsScene from './js/page/SettingsScene';
import AboutScene from './js/page/AboutScene';
import SetMottoScene from './js/page/SetMottoScene';
import theme from 'react-native-theme';

theme.add(require('./js/style/darkTheme'));
theme.add(require('./js/style/lightTheme'), 'light');
import DatePickerScene from './js/page/DatePickerScene';

class RN_Bref extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      touchIdEnabled: null,
      touchIdSet: null,
      authSuccess: null,
      lightModeEnabled: false
    }
  }

  async _loadInitialState() {
    await AsyncStorage.getItem('@Bref:TouchIdEnabled')
      .then(result => {
        if (result !== null) {
          this.setState({touchIdEnabled: result === 'true', touchIdSet: true});
        } else {
          this.setState({touchIdSet: false});
        }
      })
      .catch(error => {
        console.log(error);
      });

    await AsyncStorage.getItem('@Bref:LightModeEnabled')
      .then(result => {
        console.log('Load initial state LightModeEnabled: ' + result);
        if (result !== null && result == 'true') {
          theme.active('light');
          this.setState({lightModeEnabled: result == 'true'});
        }
        else {
          this.setState({lightModeEnabled: false});
        }
      })
      .catch(error => {
        console.log(error);
      });
  }

  componentWillMount() {
    this._loadInitialState().done();
  }

  _showTouchId(needShow) {
    if (needShow) {
      PasscodeAuth.authenticate('Unlock Bref')
        .then(success => {
          console.log('passcode auth success');
          this.setState({authSuccess: true});
        })
        .catch(error => {
          switch (error.message) {
            case 'LAErrorUserCancel':
              console.log('user cancel');
              break;
            case 'LAErrorAuthenticationFailed	':
              console.log('authenticate fail');
              break;
            case 'LAErrorUserFallback':
              console.log('user fallback');
              break;
            case 'LAErrorPasscodeNotSet':
              console.log('passcode not set');
              AlertIOS.alert('Passcode not set');
              break;
            case 'PasscodeAuthNotSupported':
              console.log('passcode auth not supported');
              AlertIOS.alert('Passcode auth not supported');
              break;
            default:
              break;
          }
        })
    }
  }

  async componentDidMount() {
    await setTimeout(() => {
      this._showTouchId(this.state.touchIdEnabled);
    }, 300);
  }

  render() {
    if (this.state.touchIdEnabled == null && this.state.touchIdSet === null) {
      return (<View></View>);
    } else if (this.state.touchIdSet === false
      || (this.state.touchIdSet === true && this.state.touchIdEnabled === false)
      || this.state.authSuccess === true) {
      return (
        <Navigator
          initialRoute={{scene: 'Initial'}}
          renderScene={RN_Bref.navigatorRenderScene}
          navigationBar={
            <Navigator.NavigationBar
              routeMapper={{
                LeftButton: (route, navigator, index, navState) => {
                  if (route.scene === 'Initial') {
                    return null;
                  } else {
                    return (
                      <TouchableHighlight style={{alignItems: 'center'}} onPress={() => navigator.pop()}>
                        <Icon name="chevron-left" style={navStyle.navButtonLeft}/>
                      </TouchableHighlight>
                    );
                  }
                },
                RightButton: (route, navigator, index, navState) => {
                  if (route.scene === 'New' || route.scene === 'Set Motto') {
                    return (

                      <TouchableHighlight
                        style={{alignItems: 'center'}}
                        onPress={() => navigator.pop()}
                      >
                        <Icon name="check-square-o" style={navStyle.navButtonRight}/>
                      </TouchableHighlight>

                    );
                  }
                  else {
                    return null;
                  }
                },
                Title: (route, navigator, index, navState) => {
                  var title = null;
                  title = route.scene;
                  if (title != 'Initial') {
                    return (
                      <Text style={navStyle.navBarTitle}>
                        {title}
                      </Text>
                    );
                  }
                }
              }}
              style={{backgroundColor: 'black'}}
            />
          }
        />
      );
    }
  }

  static navigatorRenderScene(route, navigator) {
    switch (route.scene) {
      case 'Initial':
        return (<OriginalScene navigator={navigator}/>);
      case 'New':
        return (<NewScene navigator={navigator}/>);
      case 'Timeline':
        return (<TimelineScene navigator={navigator}/>);
      case 'Sites':
        return (<SitesScene navigator={navigator}/>);
      case 'Settings':
        return (<SettingsScene navigator={navigator}/>);
      case 'About':
        return (<AboutScene navigator={navigator}/>);
      case 'Set Motto':
        return (<SetMottoScene navigator={navigator}/>);
      case 'Date Picker':
        return (<DatePickerScene navigator={navigator}/>);
      default:
        return (<OriginalScene navigator={navigator}/>);
    }
  }
}

AppRegistry.registerComponent('RN_Bref', () => RN_Bref);

const navStyle = StyleSheet.create({
  navButtonLeft: {
    marginLeft: 25,
    marginTop: 10,
    fontSize: 20,
    color: 'white'
  },
  navButtonRight: {
    marginRight: 25,
    marginTop: 10,
    fontSize: 25,
    color: 'white'
  },
  navBarTitle: {
    marginTop: 10,
    fontSize: 20,
    color: 'white',
    fontWeight: 'bold'
  }
});<commit_msg>navigator style setting<commit_after>'use strict';

import React, {Component} from 'react';
import {
  AppRegistry,
  Navigator,
  Text,
  View,
  TouchableHighlight,
  StyleSheet,
  AsyncStorage
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import PasscodeAuth from 'react-native-passcode-auth';

import OriginalScene from './js/page/OriginalScene';
import NewScene from './js/page/NewScene';
import TimelineScene from './js/page/TimelineScene';
import SitesScene from './js/page/SitesScene';
import SettingsScene from './js/page/SettingsScene';
import AboutScene from './js/page/AboutScene';
import SetMottoScene from './js/page/SetMottoScene';
import theme from 'react-native-theme';

theme.add(require('./js/style/darkTheme'));
theme.add(require('./js/style/lightTheme'), 'light');
import DatePickerScene from './js/page/DatePickerScene';
import {styles} from 'react-native-theme';

class RN_Bref extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      touchIdEnabled: null,
      touchIdSet: null,
      authSuccess: null,
      lightModeEnabled: false
    }
  }

  async _loadInitialState() {
    await AsyncStorage.getItem('@Bref:TouchIdEnabled')
      .then(result => {
        if (result !== null) {
          this.setState({touchIdEnabled: result === 'true', touchIdSet: true});
        } else {
          this.setState({touchIdSet: false});
        }
      })
      .catch(error => {
        console.log(error);
      });

    await AsyncStorage.getItem('@Bref:LightModeEnabled')
      .then(result => {
        console.log('Load initial state LightModeEnabled: ' + result);
        if (result !== null && result == 'true') {
          theme.active('light');
          this.setState({lightModeEnabled: result == 'true'});
        }
        else {
          this.setState({lightModeEnabled: false});
        }
      })
      .catch(error => {
        console.log(error);
      });
  }

  componentWillMount() {
    this._loadInitialState().done();
  }

  _showTouchId(needShow) {
    if (needShow) {
      PasscodeAuth.authenticate('Unlock Bref')
        .then(success => {
          console.log('passcode auth success');
          this.setState({authSuccess: true});
        })
        .catch(error => {
          switch (error.message) {
            case 'LAErrorUserCancel':
              console.log('user cancel');
              break;
            case 'LAErrorAuthenticationFailed	':
              console.log('authenticate fail');
              break;
            case 'LAErrorUserFallback':
              console.log('user fallback');
              break;
            case 'LAErrorPasscodeNotSet':
              console.log('passcode not set');
              AlertIOS.alert('Passcode not set');
              break;
            case 'PasscodeAuthNotSupported':
              console.log('passcode auth not supported');
              AlertIOS.alert('Passcode auth not supported');
              break;
            default:
              break;
          }
        })
    }
  }

  async componentDidMount() {
    await setTimeout(() => {
      this._showTouchId(this.state.touchIdEnabled);
    }, 300);
  }

  render() {
    if (this.state.touchIdEnabled == null && this.state.touchIdSet === null) {
      return (<View></View>);
    } else if (this.state.touchIdSet === false
      || (this.state.touchIdSet === true && this.state.touchIdEnabled === false)
      || this.state.authSuccess === true) {
      return (
        <Navigator
          initialRoute={{scene: 'Initial'}}
          renderScene={RN_Bref.navigatorRenderScene}
          navigationBar={
            <Navigator.NavigationBar
              routeMapper={{
                LeftButton: (route, navigator, index, navState) => {
                  if (route.scene === 'Initial') {
                    return null;
                  } else {
                    return (
                      <TouchableHighlight style={{alignItems: 'center'}} onPress={() => navigator.pop()}>
                        <Icon name="chevron-left" style={[navStyle.navButtonLeft, styles.navContentColor]}/>
                      </TouchableHighlight>
                    );
                  }
                },
                RightButton: (route, navigator, index, navState) => {
                  if (route.scene === 'New' || route.scene === 'Set Motto') {
                    return (
                      <TouchableHighlight
                        style={{alignItems: 'center'}}
                        onPress={() => navigator.pop()}
                      >
                        <Icon name="check-square-o" style={[navStyle.navButtonRight, styles.navContentColor]}/>
                      </TouchableHighlight>
                    );
                  }
                  else {
                    return null;
                  }
                },
                Title: (route, navigator, index, navState) => {
                  var title = null;
                  title = route.scene;
                  if (title != 'Initial') {
                    return (
                      <Text style={[navStyle.navBarTitle,styles.navContentColor]}>
                        {title}
                      </Text>
                    );
                  }
                }
              }}
              style={styles.navBackground}
            />
          }
        />
      );
    }
  }

  static navigatorRenderScene(route, navigator) {
    switch (route.scene) {
      case 'Initial':
        return (<OriginalScene navigator={navigator}/>);
      case 'New':
        return (<NewScene navigator={navigator}/>);
      case 'Timeline':
        return (<TimelineScene navigator={navigator}/>);
      case 'Sites':
        return (<SitesScene navigator={navigator}/>);
      case 'Settings':
        return (<SettingsScene navigator={navigator}/>);
      case 'About':
        return (<AboutScene navigator={navigator}/>);
      case 'Set Motto':
        return (<SetMottoScene navigator={navigator}/>);
      case 'Date Picker':
        return (<DatePickerScene navigator={navigator}/>);
      default:
        return (<OriginalScene navigator={navigator}/>);
    }
  }
}

AppRegistry.registerComponent('RN_Bref', () => RN_Bref);

const navStyle = StyleSheet.create({
  navButtonLeft: {
    marginLeft: 25,
    marginTop: 10,
    fontSize: 20
  },
  navButtonRight: {
    marginRight: 25,
    marginTop: 10,
    fontSize: 25
  },
  navBarTitle: {
    marginTop: 10,
    fontSize: 20,
    fontWeight: 'bold'
  }
});<|endoftext|>


<commit_before>var del     = require("del");
var bower	  = require("bower");
var gulp    = require("gulp");
var less    = require("gulp-less");
var rename  = require("gulp-rename");
var minify  = require("gulp-minify-css");

var paths = {
  bowerDir : "bower_components/",
  lessSrc : "src/less/sugar.less",
  cssDest : "dist/css/",
  fontDest : "dist/fonts"
};

gulp.task("default", ["build"]);

gulp.task("build", ["clean", "less", "fonts"]);

gulp.task("clean", function(cb) {
  del("dist", cb);
});

gulp.task("less", ["bower"], function() {
  gulp.src(paths.lessSrc)
  .pipe(less())
  .pipe(rename("sugar.css"))
  .pipe(gulp.dest(paths.cssDest))
  .pipe(minify())
  .pipe(rename("sugar.min.css"))
  .pipe(gulp.dest(paths.cssDest));
});

gulp.task("fonts", ["bower"], function() {
  gulp.src(paths.bowerDir + "font-awesome/fonts/*.*")
  .pipe(gulp.dest(paths.fontDest));
});

gulp.task("bower", function(cb) {
  bower.commands.install()
  .on("end", function() {
    cb();
  });
});
<commit_msg>one line<commit_after>var del     = require("del");
var bower	  = require("bower");
var gulp    = require("gulp");
var less    = require("gulp-less");
var rename  = require("gulp-rename");
var minify  = require("gulp-minify-css");

var paths = {
  lessSrc : "src/less/sugar.less",
  cssDest : "dist/css/",
  fontDest : "dist/fonts"
  bowerDir : "bower_components/",
};

gulp.task("default", ["build"]);

gulp.task("build", ["clean", "less", "fonts"]);

gulp.task("clean", function(cb) {
  del("dist", cb);
});

gulp.task("less", ["bower"], function() {
  gulp.src(paths.lessSrc)
  .pipe(less())
  .pipe(rename("sugar.css"))
  .pipe(gulp.dest(paths.cssDest))
  .pipe(minify())
  .pipe(rename("sugar.min.css"))
  .pipe(gulp.dest(paths.cssDest));
});

gulp.task("fonts", ["bower"], function() {
  gulp.src(paths.bowerDir + "font-awesome/fonts/*.*")
  .pipe(gulp.dest(paths.fontDest));
});

gulp.task("bower", function(cb) {
  bower.commands.install()
  .on("end", function() {
    cb();
  });
});
<|endoftext|>


<commit_before>define(function(require) {

    'use strict';

    var _       = require('underscore');
    var PIXI    = require('pixi');
    //var Vector2 = require('common/math/vector2');
    var PiecewiseCurve = require('common/math/piecewise-curve');
    var Colors = require('common/colors/colors');

    var ElementView = require('views/element');
    //var Beaker      = require('models/element/beaker');
    //var Assets      = require('assets');
    var EnergyChunkContainerSliceView = require('views/energy-chunk-container-slice');

    var Constants = require('constants');
    var BV = Constants.BeakerView;

    // Generate a texture to use as the steam particle
    var steamParticleTexture = PIXI.Texture.generateRoundParticleTexture(0, BV.STEAM_PARTICLE_RADIUS_RANGE.max, BV.STEAM_PARTICLE_COLOR);

    /**
     * A view that represents a block model
     */
    var BeakerView = ElementView.extend({

        events: {
            'touchstart      .backLayer': 'dragStart',
            'mousedown       .backLayer': 'dragStart',
            'touchmove       .backLayer': 'drag',
            'mousemove       .backLayer': 'drag',
            'touchend        .backLayer': 'dragEnd',
            'mouseup         .backLayer': 'dragEnd',
            'touchendoutside .backLayer': 'dragEnd',
            'mouseupoutside  .backLayer': 'dragEnd',
        },

        /**
         *
         */
        initialize: function(options) {
            options = _.extend({
                fillColor: BeakerView.FILL_COLOR,
                fillAlpha: BeakerView.FILL_ALPHA,
                lineWidth: BeakerView.LINE_WIDTH,
                lineColor: BeakerView.LINE_COLOR,
                lineJoin:  'round',
                textFont:  BeakerView.TEXT_FONT,

                fluidFillColor: BeakerView.WATER_FILL_COLOR,
                fluidFillAlpha: BeakerView.WATER_FILL_ALPHA,
                fluidLineColor: BeakerView.WATER_LINE_COLOR,
                fluidLineWidth: BeakerView.WATER_LINE_WIDTH,

                dragLayer: 'backLayer'
            }, options);

            this.fluidFillColor = options.fluidFillColor;
            this.fluidFillAlpha = options.fluidFillAlpha;
            this.fluidLineColor = options.fluidLineColor;
            this.fluidLineWidth = options.fluidLineWidth;

            this.fluidFillColorHex = Colors.parseHex(this.fluidFillColor);
            this.fluidLineColorHex = Colors.parseHex(this.fluidLineColor);

            ElementView.prototype.initialize.apply(this, [options]);

            this.listenTo(this.model, 'change:fluidLevel', this.updateFluidLevel);
            this.updateFluidLevel(this.model, this.model.get('fluidLevel'));
        },

        initGraphics: function() {
            this.backLayer        = new PIXI.DisplayObjectContainer();
            this.energyChunkLayer = new PIXI.DisplayObjectContainer();
            this.frontLayer       = new PIXI.DisplayObjectContainer();

            // Get a version of the rectangle that defines the beaker size and
            //   location in the view.
            this.beakerViewRect = this.mvt.modelToViewScale(this.model.getRawOutlineRect()).clone();
            this.ellipseHeight = this.beakerViewRect.w * BeakerView.PERSPECTIVE_PROPORTION;

            this.initBeaker();
            this.initFluid();
            this.initLabel();
            this.initEnergyChunks();
            this.initSteam();

            // Calculate the bounding box for the dragging bounds
            this.boundingBox = this.beakerViewRect.clone();
        },

        initBeaker: function() {
            // Create the shapes for the top and bottom of the beaker.  These are
            //   ellipses in order to create a 3D-ish look.
            var backCurves  = new PiecewiseCurve();
            var frontCurves = new PiecewiseCurve();
            var backFill  = new PiecewiseCurve();
            var frontFill = new PiecewiseCurve();

            var top    = this.beakerViewRect.bottom() - this.beakerViewRect.h;
            var bottom = this.beakerViewRect.bottom();
            var left   = this.beakerViewRect.left();
            var right  = this.beakerViewRect.right();
            var ellipseHeight = this.ellipseHeight;

            // Front fill
            frontFill
                .moveTo(left, bottom)
                .curveTo(
                    left,  bottom + ellipseHeight / 2,
                    right, bottom + ellipseHeight / 2,
                    right, bottom
                )
                .lineTo(right, top)
                .curveTo(
                    right, top + ellipseHeight / 2,
                    left,  top + ellipseHeight / 2,
                    left,  top
                )
                .lineTo(left, bottom)
                .close();
            // Back fill (the top little ellipse area)
            backFill
                .moveTo(left, top)
                .curveTo(
                    left,  top - ellipseHeight / 2,
                    right, top - ellipseHeight / 2,
                    right, top
                )
                .moveTo(left, top)
                .curveTo(
                    left,  top + ellipseHeight / 2,
                    right, top + ellipseHeight / 2,
                    right, top
                );

            var fillStyle = {
                lineWidth: 0,
                fillStyle: this.fillColor,
                fillAlpha: this.fillAlpha
            };

            this.frontLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(frontFill, fillStyle));
            this.backLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(backFill, fillStyle));

            // Top back curve
            backCurves
                .moveTo(left, top)
                .curveTo(
                    left,  top - ellipseHeight / 2,
                    right, top - ellipseHeight / 2,
                    right, top
                );
            // Top front curve
            frontCurves
                .moveTo(left, top)
                .curveTo(
                    left,  top + ellipseHeight / 2,
                    right, top + ellipseHeight / 2,
                    right, top
                );
            // Bottom back curve
            backCurves
                .moveTo(left, bottom)
                .curveTo(
                    left,  bottom - ellipseHeight / 2,
                    right, bottom - ellipseHeight / 2,
                    right, bottom
                );
            // Bottom front curve
            frontCurves
                .moveTo(left, bottom)
                .curveTo(
                    left,  bottom + ellipseHeight / 2,
                    right, bottom + ellipseHeight / 2,
                    right, bottom
                );
            // Vertical edges
            frontCurves
                .moveTo(left, bottom)
                .lineTo(left, top)
                .moveTo(right, bottom)
                .lineTo(right, top);

            // Outline style
            var lineStyle = {
                lineWidth:   this.lineWidth,
                strokeStyle: this.lineColor,
                lineJoin:    this.lineJoin
            };

            this.backLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(backCurves, lineStyle));
            this.frontLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(frontCurves, lineStyle));
        },

        initFluid: function() {
            var left  = this.beakerViewRect.left();
            var right = this.beakerViewRect.right();
            var ellipseHeight = this.ellipseHeight;

            var fluidTopCurve = new PiecewiseCurve();
            fluidTopCurve
                .moveTo(left, 0)
                .curveTo(
                    left,  -ellipseHeight / 2,
                    right, -ellipseHeight / 2,
                    right, 0
                )
                .curveTo(
                    right, ellipseHeight / 2,
                    left,  ellipseHeight / 2,
                    left,  0
                );

            var fluidStyle = {
                fillStyle:   this.fluidFillColor,
                fillAlpha:   this.fluidFillAlpha,
                strokeStyle: this.fluidLineColor,
                lineWidth:   this.fluidLineWidth
            };

            this.fluidTop = PIXI.Sprite.fromPiecewiseCurve(fluidTopCurve, fluidStyle);
            this.fluidFront = new PIXI.Graphics();

            this.fluidLayer = new PIXI.DisplayObjectContainer();
            this.fluidLayer.addChild(this.fluidFront);
            this.fluidLayer.addChild(this.fluidTop);

            this.frontLayer.addChildAt(this.fluidLayer, 0);

            this.fluidMask = new PIXI.Graphics();
            this.energyChunkLayer.addChild(this.fluidMask);
        },

        initLabel: function() {
            // Label
            this.label = new PIXI.Text(this.labelText, {
                font: this.textFont,
                fill: this.textColor
            });
            this.label.anchor.x = this.label.anchor.y = 0.5;
            this.label.x = 0;
            this.label.y = -(this.beakerViewRect.h / 2);
            this.frontLayer.addChild(this.label);
        },

        initEnergyChunks: function() {
            this.energyChunkLayer.visible = false;
            this.energyChunkLayer.mask = this.fluidMask;

            _.each(this.model.slices, function(slice) {
                var view = new EnergyChunkContainerSliceView({
                    slice: slice,
                    mvt: this.mvt
                });
                this.energyChunkLayer.addChild(view.displayObject);
            }, this);
        },

        initSteam: function() {
            this.steamLayer = new PIXI.SpriteBatch();
            this.fluidLayer.addChild(this.steamLayer);

            this.activeSteamParticles = [];
            this.dormantSteamParticles = [];
            var particle;
            for (var i = 0; i < BeakerView.NUM_STEAM_PARTICLES; i++) {
                particle = new PIXI.Sprite(steamParticleTexture);
                particle.visible = false;
                this.steamLayer.addChild(particle);
                this.dormantSteamParticles.push(particle);
            }

            this.particleProductionRemainder = 0;
        },

        activateSteamParticle: function(time, scale, x, y) {
            if (!this.dormantSteamParticles.length)
                return null;

            var particle = this.dormantSteamParticles.pop();
            particle.x = x;
            particle.y = y;
            particle.scale.x = particle.scale.y = scale;
            particle.anchor.x = particle.anchor.y = 0.5;
            particle.alpha = 0;
            particle.visible = true;
            particle.timeToLive = BeakerView.STEAM_PARTICLE_LIFE_RANGE.random()
            particle.lifeEndsAt = time + particle.timeToLive;
            this.activeSteamParticles.push(particle);

            return particle;
        },

        reset: function() {
            ElementView.prototype.reset.apply(this);

        },

        calculateDragBounds: function(dx, dy) {
            var bounds = this.backLayer.getBounds();
            return this._dragBounds.set(
                bounds.x + dx,
                bounds.y + dy,
                bounds.width,
                bounds.height - this.lineWidth
            );
        },

        showEnergyChunks: function() {
            this.fluidTop.alpha = this.fluidFront.alpha = 0.8;
            this.energyChunkLayer.visible = true;
        },

        hideEnergyChunks: function() {
            this.fluidTop.alpha = this.fluidFront.alpha = 1;
            this.energyChunkLayer.visible = false;
        },

        updateFluidLevel: function(model, fluidLevel) {
            var top    = (this.beakerViewRect.bottom() - this.beakerViewRect.h) * fluidLevel;
            var bottom = this.beakerViewRect.bottom();
            var left   = this.beakerViewRect.left();
            var right  = this.beakerViewRect.right();
            var ellipseHeight = this.ellipseHeight;

            this.fluidTop.y = top;

            this.fluidFront
                .clear()
                .beginFill(this.fluidFillColorHex, this.fluidFillAlpha)
                .lineStyle(this.fluidLineWidth, this.fluidLineColorHex, 1)
                .moveTo(left, top)
                .bezierCurveTo(
                    left,  top + ellipseHeight / 2,
                    right, top + ellipseHeight / 2,
                    right, top
                )
                .lineTo(right, bottom)
                .bezierCurveTo(
                    right, bottom + ellipseHeight / 2,
                    left,  bottom + ellipseHeight / 2,
                    left,  bottom
                )
                .lineTo(left, top)
                .endFill();

            this.fluidMask
                .clear()
                .beginFill(0x000000, 1)
                .moveTo(left, top)
                .bezierCurveTo(
                    left,  top -ellipseHeight / 2,
                    right, top -ellipseHeight / 2,
                    right, top
                )
                .lineTo(right, bottom)
                .bezierCurveTo(
                    right, bottom + ellipseHeight / 2,
                    left,  bottom + ellipseHeight / 2,
                    left,  bottom
                )
                .lineTo(left, top)
                .moveTo(left + 20, bottom - 20)
                .lineTo(left + 40, bottom - 40)
                .lineTo(left + 60, bottom - 20)
                .lineTo(left + 20, bottom - 20)
                .endFill();
        },

        updatePosition: function(model, position) {
            var viewPoint = this.mvt.modelToView(position);
            this.backLayer.x = this.frontLayer.x = this.energyChunkLayer.x = viewPoint.x;
            this.backLayer.y = this.frontLayer.y = this.energyChunkLayer.y = viewPoint.y;
        },

        updateSteam: function(time, deltaTime) {
            var fluidTop = (this.beakerViewRect.bottom() - this.beakerViewRect.h) * this.model.get('fluidLevel');

            var steamingProportion = 0;
            if (Constants.BOILING_POINT_TEMPERATURE - this.model.getTemperature() < BeakerView.STEAMING_RANGE) {
                // Water is emitting some amount of steam.  Set the proportionate amount.
                steamingProportion = 1 - ((Constants.BOILING_POINT_TEMPERATURE - this.model.getTemperature()) / BeakerView.STEAMING_RANGE);
                steamingProportion = Math.min(1, Math.max(steamingProportion, 0));
            }
            //steamingProportion = 0.7;
            //console.log(this.model.getTemperature());

            // Add any new steam particles
            if (steamingProportion > 0) {
                var particlesToProduce = BeakerView.STEAM_PARTICLE_PRODUCTION_RATE_RANGE.lerp(steamingProportion) * deltaTime;

                this.particleProductionRemainder += particlesToProduce % 1;
                if (this.particleProductionRemainder >= 1) {
                    particlesToProduce += Math.floor(this.particleProductionRemainder);
                    this.particleProductionRemainder -= Math.floor(this.particleProductionRemainder);
                }
                particlesToProduce = Math.floor(particlesToProduce);

                var scale;
                var x;
                var particle;
                for (var i = 0; i < particlesToProduce; i++) {
                    scale = BeakerView.STEAM_PARTICLE_RADIUS_RANGE.random() / BeakerView.STEAM_PARTICLE_RADIUS_RANGE.max;
                    x = (Math.random() - 0.5) * (this.beakerViewRect.w - steamParticleTexture.width);
                    this.activateSteamParticle(time, scale, x, fluidTop);
                }
            }

            // Update existing steam particles
            var speed = BeakerView.STEAM_PARTICLE_SPEED_RANGE.lerp(steamingProportion);
            var unfilledBeakerHeight = this.beakerViewRect.h * (1 - this.model.get('fluidLevel'));
            var fadeInDistance = unfilledBeakerHeight / 4;
            var centerX = 0;

            var particle;
            for (var i = this.activeSteamParticles.length - 1; i >= 0; i--) {
                particle = this.activeSteamParticles[i];
                particle.y += deltaTime * -speed;

                if (time >= particle.lifeEndsAt) {
                    particle.visible = false;
                    this.activeSteamParticles.splice(i, 1);
                    this.dormantSteamParticles.push(particle);
                }
                else if (particle.y < -this.beakerViewRect.h) {
                    var scale = particle.scale.x * (1 + BeakerView.STEAM_PARTICLE_GROWTH_RATE * deltaTime);
                    particle.scale.x = particle.scale.y = scale;
                    var distanceFromCenterX = particle.x - centerX;
                    particle.x += distanceFromCenterX * 0.2 * deltaTime;

                    // Fade the particle out as it reaches the end of its life
                    particle.alpha = ((particle.lifeEndsAt - time) / particle.timeToLive) * BeakerView.MAX_STEAM_PARTICLE_OPACITY;
                }
                else {
                    // Fade the particle in
                    var distanceFromWater = fluidTop - particle.y;
                    particle.alpha = Math.min(1, Math.max(0, (distanceFromWater / fadeInDistance))) * BeakerView.MAX_STEAM_PARTICLE_OPACITY;
                }
            }
        },

        update: function(time, deltaTime, simulationPaused) {
            if (!simulationPaused)
                this.updateSteam(time, deltaTime);
        }

    }, Constants.BeakerView);

    return BeakerView;
});<commit_msg>Temporarily turned steaming always on so it can be seen<commit_after>define(function(require) {

    'use strict';

    var _       = require('underscore');
    var PIXI    = require('pixi');
    //var Vector2 = require('common/math/vector2');
    var PiecewiseCurve = require('common/math/piecewise-curve');
    var Colors = require('common/colors/colors');

    var ElementView = require('views/element');
    //var Beaker      = require('models/element/beaker');
    //var Assets      = require('assets');
    var EnergyChunkContainerSliceView = require('views/energy-chunk-container-slice');

    var Constants = require('constants');
    var BV = Constants.BeakerView;

    // Generate a texture to use as the steam particle
    var steamParticleTexture = PIXI.Texture.generateRoundParticleTexture(0, BV.STEAM_PARTICLE_RADIUS_RANGE.max, BV.STEAM_PARTICLE_COLOR);

    /**
     * A view that represents a block model
     */
    var BeakerView = ElementView.extend({

        events: {
            'touchstart      .backLayer': 'dragStart',
            'mousedown       .backLayer': 'dragStart',
            'touchmove       .backLayer': 'drag',
            'mousemove       .backLayer': 'drag',
            'touchend        .backLayer': 'dragEnd',
            'mouseup         .backLayer': 'dragEnd',
            'touchendoutside .backLayer': 'dragEnd',
            'mouseupoutside  .backLayer': 'dragEnd',
        },

        /**
         *
         */
        initialize: function(options) {
            options = _.extend({
                fillColor: BeakerView.FILL_COLOR,
                fillAlpha: BeakerView.FILL_ALPHA,
                lineWidth: BeakerView.LINE_WIDTH,
                lineColor: BeakerView.LINE_COLOR,
                lineJoin:  'round',
                textFont:  BeakerView.TEXT_FONT,

                fluidFillColor: BeakerView.WATER_FILL_COLOR,
                fluidFillAlpha: BeakerView.WATER_FILL_ALPHA,
                fluidLineColor: BeakerView.WATER_LINE_COLOR,
                fluidLineWidth: BeakerView.WATER_LINE_WIDTH,

                dragLayer: 'backLayer'
            }, options);

            this.fluidFillColor = options.fluidFillColor;
            this.fluidFillAlpha = options.fluidFillAlpha;
            this.fluidLineColor = options.fluidLineColor;
            this.fluidLineWidth = options.fluidLineWidth;

            this.fluidFillColorHex = Colors.parseHex(this.fluidFillColor);
            this.fluidLineColorHex = Colors.parseHex(this.fluidLineColor);

            ElementView.prototype.initialize.apply(this, [options]);

            this.listenTo(this.model, 'change:fluidLevel', this.updateFluidLevel);
            this.updateFluidLevel(this.model, this.model.get('fluidLevel'));
        },

        initGraphics: function() {
            this.backLayer        = new PIXI.DisplayObjectContainer();
            this.energyChunkLayer = new PIXI.DisplayObjectContainer();
            this.frontLayer       = new PIXI.DisplayObjectContainer();

            // Get a version of the rectangle that defines the beaker size and
            //   location in the view.
            this.beakerViewRect = this.mvt.modelToViewScale(this.model.getRawOutlineRect()).clone();
            this.ellipseHeight = this.beakerViewRect.w * BeakerView.PERSPECTIVE_PROPORTION;

            this.initBeaker();
            this.initFluid();
            this.initLabel();
            this.initEnergyChunks();
            this.initSteam();

            // Calculate the bounding box for the dragging bounds
            this.boundingBox = this.beakerViewRect.clone();
        },

        initBeaker: function() {
            // Create the shapes for the top and bottom of the beaker.  These are
            //   ellipses in order to create a 3D-ish look.
            var backCurves  = new PiecewiseCurve();
            var frontCurves = new PiecewiseCurve();
            var backFill  = new PiecewiseCurve();
            var frontFill = new PiecewiseCurve();

            var top    = this.beakerViewRect.bottom() - this.beakerViewRect.h;
            var bottom = this.beakerViewRect.bottom();
            var left   = this.beakerViewRect.left();
            var right  = this.beakerViewRect.right();
            var ellipseHeight = this.ellipseHeight;

            // Front fill
            frontFill
                .moveTo(left, bottom)
                .curveTo(
                    left,  bottom + ellipseHeight / 2,
                    right, bottom + ellipseHeight / 2,
                    right, bottom
                )
                .lineTo(right, top)
                .curveTo(
                    right, top + ellipseHeight / 2,
                    left,  top + ellipseHeight / 2,
                    left,  top
                )
                .lineTo(left, bottom)
                .close();
            // Back fill (the top little ellipse area)
            backFill
                .moveTo(left, top)
                .curveTo(
                    left,  top - ellipseHeight / 2,
                    right, top - ellipseHeight / 2,
                    right, top
                )
                .moveTo(left, top)
                .curveTo(
                    left,  top + ellipseHeight / 2,
                    right, top + ellipseHeight / 2,
                    right, top
                );

            var fillStyle = {
                lineWidth: 0,
                fillStyle: this.fillColor,
                fillAlpha: this.fillAlpha
            };

            this.frontLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(frontFill, fillStyle));
            this.backLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(backFill, fillStyle));

            // Top back curve
            backCurves
                .moveTo(left, top)
                .curveTo(
                    left,  top - ellipseHeight / 2,
                    right, top - ellipseHeight / 2,
                    right, top
                );
            // Top front curve
            frontCurves
                .moveTo(left, top)
                .curveTo(
                    left,  top + ellipseHeight / 2,
                    right, top + ellipseHeight / 2,
                    right, top
                );
            // Bottom back curve
            backCurves
                .moveTo(left, bottom)
                .curveTo(
                    left,  bottom - ellipseHeight / 2,
                    right, bottom - ellipseHeight / 2,
                    right, bottom
                );
            // Bottom front curve
            frontCurves
                .moveTo(left, bottom)
                .curveTo(
                    left,  bottom + ellipseHeight / 2,
                    right, bottom + ellipseHeight / 2,
                    right, bottom
                );
            // Vertical edges
            frontCurves
                .moveTo(left, bottom)
                .lineTo(left, top)
                .moveTo(right, bottom)
                .lineTo(right, top);

            // Outline style
            var lineStyle = {
                lineWidth:   this.lineWidth,
                strokeStyle: this.lineColor,
                lineJoin:    this.lineJoin
            };

            this.backLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(backCurves, lineStyle));
            this.frontLayer.addChild(PIXI.Sprite.fromPiecewiseCurve(frontCurves, lineStyle));
        },

        initFluid: function() {
            var left  = this.beakerViewRect.left();
            var right = this.beakerViewRect.right();
            var ellipseHeight = this.ellipseHeight;

            var fluidTopCurve = new PiecewiseCurve();
            fluidTopCurve
                .moveTo(left, 0)
                .curveTo(
                    left,  -ellipseHeight / 2,
                    right, -ellipseHeight / 2,
                    right, 0
                )
                .curveTo(
                    right, ellipseHeight / 2,
                    left,  ellipseHeight / 2,
                    left,  0
                );

            var fluidStyle = {
                fillStyle:   this.fluidFillColor,
                fillAlpha:   this.fluidFillAlpha,
                strokeStyle: this.fluidLineColor,
                lineWidth:   this.fluidLineWidth
            };

            this.fluidTop = PIXI.Sprite.fromPiecewiseCurve(fluidTopCurve, fluidStyle);
            this.fluidFront = new PIXI.Graphics();

            this.fluidLayer = new PIXI.DisplayObjectContainer();
            this.fluidLayer.addChild(this.fluidFront);
            this.fluidLayer.addChild(this.fluidTop);

            this.frontLayer.addChildAt(this.fluidLayer, 0);

            this.fluidMask = new PIXI.Graphics();
            this.energyChunkLayer.addChild(this.fluidMask);
        },

        initLabel: function() {
            // Label
            this.label = new PIXI.Text(this.labelText, {
                font: this.textFont,
                fill: this.textColor
            });
            this.label.anchor.x = this.label.anchor.y = 0.5;
            this.label.x = 0;
            this.label.y = -(this.beakerViewRect.h / 2);
            this.frontLayer.addChild(this.label);
        },

        initEnergyChunks: function() {
            this.energyChunkLayer.visible = false;
            this.energyChunkLayer.mask = this.fluidMask;

            _.each(this.model.slices, function(slice) {
                var view = new EnergyChunkContainerSliceView({
                    slice: slice,
                    mvt: this.mvt
                });
                this.energyChunkLayer.addChild(view.displayObject);
            }, this);
        },

        initSteam: function() {
            this.steamLayer = new PIXI.SpriteBatch();
            this.fluidLayer.addChild(this.steamLayer);

            this.activeSteamParticles = [];
            this.dormantSteamParticles = [];
            var particle;
            for (var i = 0; i < BeakerView.NUM_STEAM_PARTICLES; i++) {
                particle = new PIXI.Sprite(steamParticleTexture);
                particle.visible = false;
                this.steamLayer.addChild(particle);
                this.dormantSteamParticles.push(particle);
            }

            this.particleProductionRemainder = 0;
        },

        activateSteamParticle: function(time, scale, x, y) {
            if (!this.dormantSteamParticles.length)
                return null;

            var particle = this.dormantSteamParticles.pop();
            particle.x = x;
            particle.y = y;
            particle.scale.x = particle.scale.y = scale;
            particle.anchor.x = particle.anchor.y = 0.5;
            particle.alpha = 0;
            particle.visible = true;
            particle.timeToLive = BeakerView.STEAM_PARTICLE_LIFE_RANGE.random()
            particle.lifeEndsAt = time + particle.timeToLive;
            this.activeSteamParticles.push(particle);

            return particle;
        },

        reset: function() {
            ElementView.prototype.reset.apply(this);

        },

        calculateDragBounds: function(dx, dy) {
            var bounds = this.backLayer.getBounds();
            return this._dragBounds.set(
                bounds.x + dx,
                bounds.y + dy,
                bounds.width,
                bounds.height - this.lineWidth
            );
        },

        showEnergyChunks: function() {
            this.fluidTop.alpha = this.fluidFront.alpha = 0.8;
            this.energyChunkLayer.visible = true;
        },

        hideEnergyChunks: function() {
            this.fluidTop.alpha = this.fluidFront.alpha = 1;
            this.energyChunkLayer.visible = false;
        },

        updateFluidLevel: function(model, fluidLevel) {
            var top    = (this.beakerViewRect.bottom() - this.beakerViewRect.h) * fluidLevel;
            var bottom = this.beakerViewRect.bottom();
            var left   = this.beakerViewRect.left();
            var right  = this.beakerViewRect.right();
            var ellipseHeight = this.ellipseHeight;

            this.fluidTop.y = top;

            this.fluidFront
                .clear()
                .beginFill(this.fluidFillColorHex, this.fluidFillAlpha)
                .lineStyle(this.fluidLineWidth, this.fluidLineColorHex, 1)
                .moveTo(left, top)
                .bezierCurveTo(
                    left,  top + ellipseHeight / 2,
                    right, top + ellipseHeight / 2,
                    right, top
                )
                .lineTo(right, bottom)
                .bezierCurveTo(
                    right, bottom + ellipseHeight / 2,
                    left,  bottom + ellipseHeight / 2,
                    left,  bottom
                )
                .lineTo(left, top)
                .endFill();

            this.fluidMask
                .clear()
                .beginFill(0x000000, 1)
                .moveTo(left, top)
                .bezierCurveTo(
                    left,  top -ellipseHeight / 2,
                    right, top -ellipseHeight / 2,
                    right, top
                )
                .lineTo(right, bottom)
                .bezierCurveTo(
                    right, bottom + ellipseHeight / 2,
                    left,  bottom + ellipseHeight / 2,
                    left,  bottom
                )
                .lineTo(left, top)
                .moveTo(left + 20, bottom - 20)
                .lineTo(left + 40, bottom - 40)
                .lineTo(left + 60, bottom - 20)
                .lineTo(left + 20, bottom - 20)
                .endFill();
        },

        updatePosition: function(model, position) {
            var viewPoint = this.mvt.modelToView(position);
            this.backLayer.x = this.frontLayer.x = this.energyChunkLayer.x = viewPoint.x;
            this.backLayer.y = this.frontLayer.y = this.energyChunkLayer.y = viewPoint.y;
        },

        updateSteam: function(time, deltaTime) {
            var fluidTop = (this.beakerViewRect.bottom() - this.beakerViewRect.h) * this.model.get('fluidLevel');

            var steamingProportion = 0;
            if (Constants.BOILING_POINT_TEMPERATURE - this.model.getTemperature() < BeakerView.STEAMING_RANGE) {
                // Water is emitting some amount of steam.  Set the proportionate amount.
                steamingProportion = 1 - ((Constants.BOILING_POINT_TEMPERATURE - this.model.getTemperature()) / BeakerView.STEAMING_RANGE);
                steamingProportion = Math.min(1, Math.max(steamingProportion, 0));
            }
            steamingProportion = 0.7;
            //console.log(this.model.getTemperature());

            // Add any new steam particles
            if (steamingProportion > 0) {
                var particlesToProduce = BeakerView.STEAM_PARTICLE_PRODUCTION_RATE_RANGE.lerp(steamingProportion) * deltaTime;

                this.particleProductionRemainder += particlesToProduce % 1;
                if (this.particleProductionRemainder >= 1) {
                    particlesToProduce += Math.floor(this.particleProductionRemainder);
                    this.particleProductionRemainder -= Math.floor(this.particleProductionRemainder);
                }
                particlesToProduce = Math.floor(particlesToProduce);

                var scale;
                var x;
                var particle;
                for (var i = 0; i < particlesToProduce; i++) {
                    scale = BeakerView.STEAM_PARTICLE_RADIUS_RANGE.random() / BeakerView.STEAM_PARTICLE_RADIUS_RANGE.max;
                    x = (Math.random() - 0.5) * (this.beakerViewRect.w - steamParticleTexture.width);
                    this.activateSteamParticle(time, scale, x, fluidTop);
                }
            }

            // Update existing steam particles
            var speed = BeakerView.STEAM_PARTICLE_SPEED_RANGE.lerp(steamingProportion);
            var unfilledBeakerHeight = this.beakerViewRect.h * (1 - this.model.get('fluidLevel'));
            var fadeInDistance = unfilledBeakerHeight / 4;
            var centerX = 0;

            var particle;
            for (var i = this.activeSteamParticles.length - 1; i >= 0; i--) {
                particle = this.activeSteamParticles[i];
                particle.y += deltaTime * -speed;

                if (time >= particle.lifeEndsAt) {
                    particle.visible = false;
                    this.activeSteamParticles.splice(i, 1);
                    this.dormantSteamParticles.push(particle);
                }
                else if (particle.y < -this.beakerViewRect.h) {
                    var scale = particle.scale.x * (1 + BeakerView.STEAM_PARTICLE_GROWTH_RATE * deltaTime);
                    particle.scale.x = particle.scale.y = scale;
                    var distanceFromCenterX = particle.x - centerX;
                    particle.x += distanceFromCenterX * 0.2 * deltaTime;

                    // Fade the particle out as it reaches the end of its life
                    particle.alpha = ((particle.lifeEndsAt - time) / particle.timeToLive) * BeakerView.MAX_STEAM_PARTICLE_OPACITY;
                }
                else {
                    // Fade the particle in
                    var distanceFromWater = fluidTop - particle.y;
                    particle.alpha = Math.min(1, Math.max(0, (distanceFromWater / fadeInDistance))) * BeakerView.MAX_STEAM_PARTICLE_OPACITY;
                }
            }
        },

        update: function(time, deltaTime, simulationPaused) {
            if (!simulationPaused)
                this.updateSteam(time, deltaTime);
        }

    }, Constants.BeakerView);

    return BeakerView;
});<|endoftext|>


<commit_before>'use strict';

var gulp            = require('gulp'),
    runSequence     = require('run-sequence'),
    karma           = require('gulp-karma'),
    protractor      = require('gulp-protractor').protractor,
    webdriver       = require('gulp-protractor').webdriver,
    webdriverUpdate = require('gulp-protractor').webdriver_update,
    jshint          = require('gulp-jshint'),
    browserify      = require('browserify'),
    source          = require('vinyl-source-stream'),
    streamify       = require('gulp-streamify'),
    uglifyify       = require('uglifyify'),
    sass            = require('gulp-sass'),
    rename          = require('gulp-rename'),
    ngAnnotate      = require('browserify-ngannotate'),
    templateCache   = require('gulp-angular-templatecache'),
    refresh         = require('gulp-livereload'),
    lrserver        = require('tiny-lr')(),
    morgan          = require('morgan'),
    express         = require('express'),
    livereload      = require('connect-livereload'),
    livereloadport  = 35728,
    serverport      = 3000;

/************************************************
  Web Server
 ***********************************************/

var server = express();
// log all requests to the console
server.use(morgan('dev'));
// Add live reload
server.use(livereload({port: livereloadport}));
server.use(express.static('./build'));
// Serve index.html for all routes to leave routing up to Angular
server.all('/*', function(req, res) {
    res.sendFile('index.html', { root: 'build' });
});

/************************************************
  Gulp Development/Production Tasks
 ***********************************************/

// JSHint task
gulp.task('lint', function() {

  return gulp.src(['app/js/**/*.js', '!app/js/templates.js'])
          .pipe(jshint())
          .pipe(jshint.reporter('default'));

});

// Browserify task
gulp.task('browserify', function() {

  var b = browserify({
    basedir: '.',
    entries: './app/js/main.js',
    debug: true,
    insertGlobals: true
  });

  b.transform({
    global: true
  }, ngAnnotate);

  b.transform({
    global: true
  }, uglifyify);

  return b.bundle()
          .pipe(source('main.js'))
          .pipe(streamify(rename({suffix: '.min'})))
          .pipe(gulp.dest('build/js'))
          .pipe(refresh(lrserver));

});

// Styles task
gulp.task('styles', function() {

  return gulp.src('app/styles/main.scss')
          // The onerror handler prevents Gulp from crashing when you make a mistake in your SASS
          .pipe(sass({style: 'compressed', onError: function(e) { console.log(e); } }))
          .pipe(rename({suffix: '.min'}))
          .pipe(gulp.dest('build/css/'))
          .pipe(refresh(lrserver));

});

// Views task
gulp.task('views', function() {

  // Put our index.html in the dist folder
  gulp.src('app/index.html')
    .pipe(gulp.dest('build/'));

  // Process any other view files from app/views
  return gulp.src('app/views/**/*.html')
          .pipe(templateCache({
            standalone: true
          }))
          .pipe(gulp.dest('app/js'))
          .pipe(refresh(lrserver));

});

gulp.task('watch', function() {

  // Watch our scripts
  gulp.watch(['app/js/**/*.js'],[
    'lint',
    'browserify'
  ]);
  // Watch our styles
  gulp.watch(['app/styles/**/*.scss'], [
    'styles'
  ]);
  // Watch our views
  gulp.watch(['app/index.html', 'app/views/**/*.html'], [
    'views'
  ]);

});

// Dev task
gulp.task('dev', function() {

  // Start webserver if not already running
  try {
    server.listen(serverport);
  } catch(e) {
    console.log('Server running.');
  }
  // Start live reload
  lrserver.listen(livereloadport);

  // Run all tasks once
  runSequence('styles', 'views', 'browserify');

  // Then, run the watch task to keep tabs on changes
  gulp.start('watch');

});

/************************************************
  Gulp Testing Tasks
 ***********************************************/

// Unit test task
gulp.task('unit', function() {

  // Nonsensical source to fall back to files listened in karma.conf.js,
  // see https://github.com/lazd/gulp-karma/issues/9
  return gulp.src('./thisdoesntexist')
          .pipe(karma({
            configFile: 'test/karma.conf.js',
            action: 'run'
          }))
          .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            throw err;
          });

});

// Webdriver tasks for Protractor testing
gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver', webdriver);

// Protractor test task
gulp.task('protractor', ['webdriver-update', 'webdriver'], function() {

  return gulp.src('test/e2e/**/*.js')
          .pipe(protractor({
              configFile: 'test/protractor.conf.js'
          }))
          .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            throw err;
          });

});

// Run all tests at once
gulp.task('test', function() {

  // Start webserver if not already running
  try {
    server.listen(serverport);
  } catch(e) {
    console.log('Server running.');
  }

  // Run both unit and e2e tests
  runSequence('unit', 'protractor');

});
<commit_msg>Fix typo<commit_after>'use strict';

var gulp            = require('gulp'),
    runSequence     = require('run-sequence'),
    karma           = require('gulp-karma'),
    protractor      = require('gulp-protractor').protractor,
    webdriver       = require('gulp-protractor').webdriver,
    webdriverUpdate = require('gulp-protractor').webdriver_update,
    jshint          = require('gulp-jshint'),
    browserify      = require('browserify'),
    source          = require('vinyl-source-stream'),
    streamify       = require('gulp-streamify'),
    uglifyify       = require('uglifyify'),
    sass            = require('gulp-sass'),
    rename          = require('gulp-rename'),
    ngAnnotate      = require('browserify-ngannotate'),
    templateCache   = require('gulp-angular-templatecache'),
    refresh         = require('gulp-livereload'),
    lrserver        = require('tiny-lr')(),
    morgan          = require('morgan'),
    express         = require('express'),
    livereload      = require('connect-livereload'),
    livereloadport  = 35728,
    serverport      = 3000;

/************************************************
  Web Server
 ***********************************************/

var server = express();
// log all requests to the console
server.use(morgan('dev'));
// Add live reload
server.use(livereload({port: livereloadport}));
server.use(express.static('./build'));
// Serve index.html for all routes to leave routing up to Angular
server.all('/*', function(req, res) {
    res.sendFile('index.html', { root: 'build' });
});

/************************************************
  Gulp Development/Production Tasks
 ***********************************************/

// JSHint task
gulp.task('lint', function() {

  return gulp.src(['app/js/**/*.js', '!app/js/templates.js'])
          .pipe(jshint())
          .pipe(jshint.reporter('default'));

});

// Browserify task
gulp.task('browserify', function() {

  var b = browserify({
    basedir: '.',
    entries: './app/js/main.js',
    debug: true,
    insertGlobals: true
  });

  b.transform({
    global: true
  }, ngAnnotate);

  b.transform({
    global: true
  }, uglifyify);

  return b.bundle()
          .pipe(source('main.js'))
          .pipe(streamify(rename({suffix: '.min'})))
          .pipe(gulp.dest('build/js'))
          .pipe(refresh(lrserver));

});

// Styles task
gulp.task('styles', function() {

  return gulp.src('app/styles/main.scss')
          // The onerror handler prevents Gulp from crashing when you make a mistake in your SASS
          .pipe(sass({style: 'compressed', onError: function(e) { console.log(e); } }))
          .pipe(rename({suffix: '.min'}))
          .pipe(gulp.dest('build/css/'))
          .pipe(refresh(lrserver));

});

// Views task
gulp.task('views', function() {

  // Put our index.html in the dist folder
  gulp.src('app/index.html')
    .pipe(gulp.dest('build/'));

  // Process any other view files from app/views
  return gulp.src('app/views/**/*.html')
          .pipe(templateCache({
            standalone: true
          }))
          .pipe(gulp.dest('app/js'))
          .pipe(refresh(lrserver));

});

gulp.task('watch', function() {

  // Watch our scripts
  gulp.watch(['app/js/**/*.js'],[
    'lint',
    'browserify'
  ]);
  // Watch our styles
  gulp.watch(['app/styles/**/*.scss'], [
    'styles'
  ]);
  // Watch our views
  gulp.watch(['app/index.html', 'app/views/**/*.html'], [
    'views'
  ]);

});

// Dev task
gulp.task('dev', function() {

  // Start webserver if not already running
  try {
    server.listen(serverport);
  } catch(e) {
    console.log('Server running.');
  }
  // Start live reload
  lrserver.listen(livereloadport);

  // Run all tasks once
  runSequence('styles', 'views', 'browserify');

  // Then, run the watch task to keep tabs on changes
  gulp.start('watch');

});

/************************************************
  Gulp Testing Tasks
 ***********************************************/

// Unit test task
gulp.task('unit', function() {

  // Nonsensical source to fall back to files listed in karma.conf.js,
  // see https://github.com/lazd/gulp-karma/issues/9
  return gulp.src('./thisdoesntexist')
          .pipe(karma({
            configFile: 'test/karma.conf.js',
            action: 'run'
          }))
          .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            throw err;
          });

});

// Webdriver tasks for Protractor testing
gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver', webdriver);

// Protractor test task
gulp.task('protractor', ['webdriver-update', 'webdriver'], function() {

  return gulp.src('test/e2e/**/*.js')
          .pipe(protractor({
              configFile: 'test/protractor.conf.js'
          }))
          .on('error', function(err) {
            // Make sure failed tests cause gulp to exit non-zero
            throw err;
          });

});

// Run all tests at once
gulp.task('test', function() {

  // Start webserver if not already running
  try {
    server.listen(serverport);
  } catch(e) {
    console.log('Server running.');
  }

  // Run both unit and e2e tests
  runSequence('unit', 'protractor');

});
<|endoftext|>


<commit_before>var gulp		= require('gulp'),
	concat	 	= require('gulp-concat'),
	sourcemaps	= require('gulp-sourcemaps'),
	ignore	 	= require('gulp-ignore'),
	insert	 	= require('gulp-insert'),
	uglify	 	= require('gulp-uglify'),
	fs		 	= require('fs');

gulp.task('default', function(){
	var APP_VER = "", APP_BLD = "";
	fs.readFileSync("dist/pptxgen.js", "utf8").split('\n')
	.forEach((line)=>{
		if ( line.indexOf('var APP_VER') > -1 ) APP_VER = line.split('=')[1].trim().replace(/\"+|\;+/gi,'');
		if ( line.indexOf('var APP_BLD') > -1 ) APP_BLD = line.split('=')[1].trim().replace(/\"+|\;+/gi,'');
	});

	gulp.src(['libs/*', 'dist/pptxgen.js'])
		.pipe(concat('pptxgen.bundle.js'))
		.pipe(uglify())
		.pipe(insert.prepend('/* PptxGenJS '+APP_VER+'-'+APP_BLD+' */\n'))
		.pipe(sourcemaps.init())
		.pipe(ignore.exclude(["**/*.map"]))
		.pipe(sourcemaps.write('./'))
		.pipe(gulp.dest('dist/'));

	gulp.src(['dist/pptxgen.js'])
		.pipe(concat('pptxgen.min.js'))
		.pipe(uglify())
		.pipe(insert.prepend('/* PptxGenJS '+APP_VER+'-'+APP_BLD+' */\n'))
		.pipe(gulp.dest('dist/'));
});
<commit_msg>minor formatting update<commit_after>var gulp       = require('gulp'),
    concat     = require('gulp-concat'),
    sourcemaps = require('gulp-sourcemaps'),
    ignore     = require('gulp-ignore'),
	insert     = require('gulp-insert'),
    uglify     = require('gulp-uglify'),
	fs         = require('fs');

gulp.task('default', function(){
	var APP_VER = "", APP_BLD = "";
	fs.readFileSync("dist/pptxgen.js", "utf8").split('\n')
	.forEach((line)=>{
		if ( line.indexOf('var APP_VER') > -1 ) APP_VER = line.split('=')[1].trim().replace(/\"+|\;+/gi,'');
		if ( line.indexOf('var APP_BLD') > -1 ) APP_BLD = line.split('=')[1].trim().replace(/\"+|\;+/gi,'');
	});

	gulp.src(['libs/*', 'dist/pptxgen.js'])
        .pipe(concat('pptxgen.bundle.js'))
		.pipe(uglify())
		.pipe(insert.prepend('/* PptxGenJS '+APP_VER+'-'+APP_BLD+' */\n'))
        .pipe(sourcemaps.init())
        .pipe(ignore.exclude(["**/*.map"]))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('dist/'));

    gulp.src(['dist/pptxgen.js'])
        .pipe(concat('pptxgen.min.js'))
        .pipe(uglify())
		.pipe(insert.prepend('/* PptxGenJS '+APP_VER+'-'+APP_BLD+' */\n'))
        .pipe(gulp.dest('dist/'));
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var browserify = require('gulp-browserify');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

gulp.task('default', ['lint', 'style']);

gulp.task('lint', function() {
  gulp.src(['*.js', 'app/**/*.js', 'config/*.js', 'test/*.js'])
    .pipe(jshint({linter: require('jshint-jsx').JSXHINT}))
    .pipe(jshint.reporter(stylish));
});

gulp.task('scripts', function() {
  gulp.src('app/client.js')
    .pipe(browserify({
      debug: true,
      transform: ['reactify']
    }))
    .pipe(gulp.dest('./public/js/'));
});

gulp.task('style', function() {
  gulp.src(['*.js', 'app/controllers/*.js', 'config/*.js', 'test/*.js'])
    .pipe(jscs());
});

<commit_msg>Add gulp watch<commit_after>var gulp = require('gulp');
var browserify = require('gulp-browserify');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');

gulp.task('lint', function() {
  gulp.src(['*.js', 'app/**/*.js', 'config/*.js', 'test/*.js'])
    .pipe(jshint({linter: require('jshint-jsx').JSXHINT}))
    .pipe(jshint.reporter(stylish));
});

gulp.task('scripts', function() {
  gulp.src('app/client.js')
    .pipe(browserify({
      debug: true,
      transform: ['reactify']
    }))
    .pipe(gulp.dest('./public/js/'));
});

gulp.task('style', function() {
  gulp.src(['*.js', 'app/controllers/*.js', 'config/*.js', 'test/*.js'])
    .pipe(jscs());
});

gulp.task('watch', function() {
  gulp.watch(['app/*.js', 'app/components/*.js'], ['scripts']);
});

gulp.task('default', ['lint', 'style', 'watch']);
<|endoftext|>


<commit_before>'use strict';

/* eslint-disable eqeqeq, prefer-template */

/*!
 * Escaper
 * https://github.com/kobezzza/Escaper
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Escaper/blob/master/LICENSE
 */

const
	gulp = require('gulp'),
	$ = require('gulp-load-plugins')(),
	fs = require('fs');

const
	headRgxp = /(\/\*![\s\S]*?\*\/\n{2})/;

function getVersion() {
	const file = fs.readFileSync('./src/escaper.js');
	return /VERSION\s*[:=]\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

function getHead(opt_version) {
	return (
		'/*!\n' +
		` * Escaper${opt_version ? ` v${getVersion()}` : ''}\n` +
		' * https://github.com/kobezzza/Escaper\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/kobezzza/Escaper/blob/master/LICENSE\n'
	);
}

gulp.task('predefs:build', () =>
	gulp.src('./predefs/src/index.js')
		.pipe($.plumber())
		.pipe($.monic())
		.pipe(gulp.dest('./predefs/build'))
);

gulp.task('predefs:externs', () =>
	$.download([
		'https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/jasmine.js'
	])
		.pipe($.plumber())
		.pipe(gulp.dest('./predefs/src/ws'))
);

gulp.task('predefs:bower', () =>
	$.run('bower install').exec()
);

gulp.task('predefs', gulp.parallel([
	'predefs:build',
	'predefs:externs',
	'predefs:bower'
]));

gulp.task('build:js', () => {
	const fullHead =
		getHead(true) +
		' *\n' +
		` * Date: ${new Date().toUTCString()}\n` +
		' */\n\n';

	return gulp.src('./src/escaper.js')
		.pipe($.plumber())
		.pipe($.rollup({
			input: './src/escaper.js',
			output: {
				name: 'Escaper',
				format: 'umd',
				exports: 'named'
			},
			amd: {id: 'Escaper'},
			plugins: [require('rollup-plugin-babel')()]
		}))

		.pipe($.replace(headRgxp, ''))
		.pipe($.header(fullHead))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
});

function compile() {
	const
		glob = require('glob'),
		config = require('./gcc.json');

	return gulp.src('./dist/escaper.js')
		.pipe($.plumber())
		.pipe($.closureCompiler(Object.assign(config, {compilerPath: glob.sync(config.compilerPath)})))
		.pipe($.replace(/^\/\*[\s\S]*?\*\//, ''))
		.pipe($.wrap('(function(){\'use strict\';<%= contents %>}).call(this);'))
		.pipe($.header(`/*! Escaper v${getVersion()} | https://github.com/kobezzza/Escaper/blob/master/LICENSE */\n`))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
}

gulp.task('build:compile', gulp.series([gulp.parallel(['predefs', 'build:js']), compile]));
gulp.task('build:compile:fast', gulp.series(['build:js', compile]));
gulp.task('build', gulp.series(['build:compile', test]));

function test(dev) {
	function exec() {
		return gulp.src(`./dist/escaper${!dev ? '.min' : ''}.js`)
			.pipe($.istanbul())
			.pipe($.istanbul.hookRequire())
			.on('finish', runTests);

		function runTests() {
			return gulp.src(`./spec/${dev ? 'dev' : ' index'}_spec.js`)
				.pipe($.plumber())
				.pipe($.jasmine())
				.pipe($.istanbul.writeReports());
		}
	}

	if (dev) {
		return exec;
	}

	exec();
}

gulp.task('test', test);
gulp.task('test:dev', gulp.series(['build:js', test(true)]));
gulp.task('yaspeller', () => $.run('yaspeller ./').exec().on('error', console.error));

gulp.task('copyright', () =>
	gulp.src('./LICENSE')
		.pipe($.plumber())
		.pipe($.replace(/(Copyright \(c\) )(\d+)-?(\d*)/, (str, intro, from, to) => {
			const year = new Date().getFullYear();
			return intro + from + (to || from != year ? `-${year}` : '');
		}))

		.pipe(gulp.dest('./'))
);

gulp.task('bump', () =>
	gulp.src('./@(package-lock|package|bower).json')
		.pipe($.plumber())
		.pipe($.bump({version: getVersion()}))
		.pipe(gulp.dest('./'))
);

gulp.task('npmignore', () =>
	gulp.src('./.npmignore')
		.pipe($.plumber())
		.pipe($.replace(/([\s\S]*?)(?=# NPM ignore list)/, `${require('fs').readFileSync('./.gitignore')}\n`))
		.pipe(gulp.dest('./'))
);

gulp.task('head', () => {
	const
		fullHead = `${getHead()} */\n\n`;

	function filter(file) {
		return !headRgxp.exec(file.contents.toString()) || RegExp.$1 !== fullHead;
	}

	const paths = [
		'./@(src|spec)/*.js',
		'./@(externs|gulpfile).js',
		'./escaper.d.ts',
		'./predefs/src/index.js'
	];

	return gulp.src(paths, {base: './'})
		.pipe($.plumber())
		.pipe($.ignore.include(filter))
		.pipe($.replace(headRgxp, ''))
		.pipe($.header(fullHead))
		.pipe(gulp.dest('./'));
});

gulp.task('default', gulp.parallel([
	'copyright',
	'head',
	'build',
	'bump',
	'yaspeller',
	'npmignore'
]));

gulp.task('watch', gulp.series(['build:js', 'bump', 'yaspeller', 'npmignore', () => {
	gulp.watch('./src/escaper.js', gulp.parallel(['test:dev', 'bump']));
	gulp.watch('./spec/*.js', gulp.series('test'));
	gulp.watch('./*.md', gulp.series('yaspeller'));
	gulp.watch('./.gitignore', gulp.series('npmignore'));
}]));
<commit_msg>Fixed some bugs<commit_after>'use strict';

/* eslint-disable eqeqeq, prefer-template */

/*!
 * Escaper
 * https://github.com/kobezzza/Escaper
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Escaper/blob/master/LICENSE
 */

const
	gulp = require('gulp'),
	$ = require('gulp-load-plugins')(),
	fs = require('fs');

const
	headRgxp = /(\/\*![\s\S]*?\*\/\n{2})/;

function getVersion() {
	const file = fs.readFileSync('./src/escaper.js');
	return /VERSION\s*[:=]\s*\[(\d+,\s*\d+,\s*\d+)]/.exec(file)[1]
		.split(/\s*,\s*/)
		.join('.');
}

function getHead(opt_version) {
	return (
		'/*!\n' +
		` * Escaper${opt_version ? ` v${getVersion()}` : ''}\n` +
		' * https://github.com/kobezzza/Escaper\n' +
		' *\n' +
		' * Released under the MIT license\n' +
		' * https://github.com/kobezzza/Escaper/blob/master/LICENSE\n'
	);
}

gulp.task('predefs:build', () =>
	gulp.src('./predefs/src/index.js')
		.pipe($.plumber())
		.pipe($.monic())
		.pipe(gulp.dest('./predefs/build'))
);

gulp.task('predefs:externs', () =>
	$.download([
		'https://raw.githubusercontent.com/google/closure-compiler/master/contrib/externs/jasmine.js'
	])
		.pipe($.plumber())
		.pipe(gulp.dest('./predefs/src/ws'))
);

gulp.task('predefs:bower', () =>
	$.run('bower install').exec()
);

gulp.task('predefs', gulp.parallel([
	'predefs:build',
	'predefs:externs',
	'predefs:bower'
]));

gulp.task('build:js', () => {
	const fullHead =
		getHead(true) +
		' *\n' +
		` * Date: ${new Date().toUTCString()}\n` +
		' */\n\n';

	return gulp.src('./src/escaper.js')
		.pipe($.plumber())
		.pipe($.rollup({
			input: './src/escaper.js',
			output: {
				name: 'Escaper',
				format: 'umd',
				exports: 'named'
			},
			amd: {id: 'Escaper'},
			plugins: [require('rollup-plugin-babel')()]
		}))

		.pipe($.replace(headRgxp, ''))
		.pipe($.header(fullHead))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
});

function compile() {
	const
		glob = require('glob'),
		config = require('./gcc.json');

	return gulp.src('./dist/escaper.js')
		.pipe($.plumber())
		.pipe($.closureCompiler(Object.assign(config, {compilerPath: glob.sync(config.compilerPath)})))
		.pipe($.replace(/^\/\*[\s\S]*?\*\//, ''))
		.pipe($.wrap('(function(){\'use strict\';<%= contents %>}).call(this);'))
		.pipe($.header(`/*! Escaper v${getVersion()} | https://github.com/kobezzza/Escaper/blob/master/LICENSE */\n`))
		.pipe($.eol('\n'))
		.pipe(gulp.dest('./dist'));
}

gulp.task('build:compile', gulp.series([gulp.parallel(['predefs', 'build:js']), compile]));
gulp.task('build:compile:fast', gulp.series(['build:js', compile]));
gulp.task('build', gulp.series(['build:compile', test]));

function test() {
	const
		dev = arguments[0] === true;

	function exec() {
		return gulp.src(`./dist/escaper${!dev ? '.min' : ''}.js`)
			.pipe($.istanbul())
			.pipe($.istanbul.hookRequire())
			.on('finish', runTests);

		function runTests() {
			return gulp.src(`./spec/${dev ? 'dev' : 'index'}_spec.js`)
				.pipe($.plumber())
				.pipe($.jasmine())
				.pipe($.istanbul.writeReports());
		}
	}

	if (dev) {
		return exec;
	}

	return exec();
}

gulp.task('test', test);
gulp.task('test:dev', gulp.series(['build:js', test(true)]));
gulp.task('yaspeller', () => $.run('yaspeller ./').exec().on('error', console.error));

gulp.task('copyright', () =>
	gulp.src('./LICENSE')
		.pipe($.plumber())
		.pipe($.replace(/(Copyright \(c\) )(\d+)-?(\d*)/, (str, intro, from, to) => {
			const year = new Date().getFullYear();
			return intro + from + (to || from != year ? `-${year}` : '');
		}))

		.pipe(gulp.dest('./'))
);

gulp.task('bump', () =>
	gulp.src('./@(package-lock|package|bower).json')
		.pipe($.plumber())
		.pipe($.bump({version: getVersion()}))
		.pipe(gulp.dest('./'))
);

gulp.task('npmignore', () =>
	gulp.src('./.npmignore')
		.pipe($.plumber())
		.pipe($.replace(/([\s\S]*?)(?=# NPM ignore list)/, `${require('fs').readFileSync('./.gitignore')}\n`))
		.pipe(gulp.dest('./'))
);

gulp.task('head', () => {
	const
		fullHead = `${getHead()} */\n\n`;

	function filter(file) {
		return !headRgxp.exec(file.contents.toString()) || RegExp.$1 !== fullHead;
	}

	const paths = [
		'./@(src|spec)/*.js',
		'./@(externs|gulpfile).js',
		'./escaper.d.ts',
		'./predefs/src/index.js'
	];

	return gulp.src(paths, {base: './'})
		.pipe($.plumber())
		.pipe($.ignore.include(filter))
		.pipe($.replace(headRgxp, ''))
		.pipe($.header(fullHead))
		.pipe(gulp.dest('./'));
});

gulp.task('default', gulp.parallel([
	'copyright',
	'head',
	'build',
	'bump',
	'yaspeller',
	'npmignore'
]));

gulp.task('watch', gulp.series(['default', () => {
	gulp.watch('./src/escaper.js', gulp.parallel(['test', 'bump']));
	gulp.watch('./spec/*.js', gulp.series('test'));
	gulp.watch('./*.md', gulp.series('yaspeller'));
	gulp.watch('./.gitignore', gulp.series('npmignore'));
}]));

gulp.task('watch:dev', gulp.series([gulp.parallel(['build:js', 'bump', 'yaspeller', 'npmignore']), () => {
	gulp.watch('./src/escaper.js', gulp.parallel(['test:dev', 'bump']));
	gulp.watch('./spec/*.js', gulp.series('test'));
	gulp.watch('./*.md', gulp.series('yaspeller'));
	gulp.watch('./.gitignore', gulp.series('npmignore'));
}]));
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var eslint = require('gulp-eslint');
var through = require('through2');

gulp.task('coverage', function() {
  return gulp.src(['index.js', 'lib/**/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['coverage'], function() {
  return gulp.src('test/*.js')
    .pipe(mocha({reporter: 'spec'}))
    .pipe(istanbul.writeReports());
});

gulp.task('lint', function() {
  return gulp.src(['*.js', 'lib/**/*.js', 'test/*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('vars', function() {
  var utils = require('./lib/utils');
  var keys = Object.keys(utils);
  var report = {};
  var cache = {};

  return gulp.src(['index.js', 'lib/**/*.js'])
    .pipe(through.obj(function(file, enc, next) {
      var str = file.contents.toString();
      keys.forEach(function(key) {
        report[key] = report[key] || 0;
        var re = cache[key] || (cache[key] = new RegExp('\\.' + key, 'g'));
        var m = str.match(re);
        if (!m) return;
        report[key]++;
      });

      next(null, file);
    }, function(next) {
      var keys = Object.keys(report);
      var res = {};

      keys.sort(function(a, b) {
        return report[a] > report[b] ? -1 : 1;
      });

      keys.forEach(function(key) {
        res[key] = report[key];
      });

      console.log(res);
      console.log(keys.length, 'modules');
      next();
    }))
});
gulp.task('default', ['test', 'lint']);
<commit_msg>use gulp-unused<commit_after>'use strict';

var gulp = require('gulp');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var eslint = require('gulp-eslint');
var unused = require('gulp-unused');

gulp.task('coverage', function() {
  return gulp.src(['index.js', 'lib/**/*.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['coverage'], function() {
  return gulp.src('test/*.js')
    .pipe(mocha({reporter: 'spec'}))
    .pipe(istanbul.writeReports());
});

gulp.task('lint', function() {
  return gulp.src(['*.js', 'lib/**/*.js', 'test/*.js'])
    .pipe(eslint())
    .pipe(eslint.format());
});

gulp.task('unused', function() {
  return gulp.src(['index.js', 'lib/**/*.js'])
    .pipe(unused({keys: Object.keys(require('./lib/utils.js'))}))
});

gulp.task('default', ['test', 'lint']);
<|endoftext|>