<commit_before>// An All Components Screen is a great way to dev and quick-test components
import React, { View, ScrollView, Text, TouchableOpacity, PropTypes } from 'react-native'
import { connect } from 'react-redux'
import styles from './Styles/AllComponentsScreenStyle'
import ProgressiveImage from '../Components/ProgressiveImage'
import { Colors, Images, Metrics } from '../Themes'
import Actions from '../Actions/Creators'
import Routes from '../Navigation/Routes'
// external libs
import Icon from 'react-native-vector-icons/FontAwesome'
import Animatable from 'react-native-animatable'
import PushNotification from 'react-native-push-notification'

// I18n
import I18n from '../I18n/I18n.js'

export default class AllComponentsScreen extends React.Component {

  constructor (props) {
    super(props)
    this.state = {}
    this.handlePressLogin = this.handlePressLogin.bind(this)
    this.handlePressLogout = this.handlePressLogout.bind(this)
    this.handlePressRocket = this.handlePressRocket.bind(this)
    this.handlePressSend = this.handlePressSend.bind(this)
    this.handlePressStar = this.handlePressStar.bind(this)
  }

  static propTypes = {
    navigator: PropTypes.object.isRequired,
    loggedIn: PropTypes.bool,
    dispatch: PropTypes.func,
    temperature: PropTypes.number,
    city: PropTypes.string
  };

  componentWillMount () {
    this.props.navigator.state.tapHamburger = () => {
      this.props.navigator.drawer.toggle()
    }
  }

  componentWillReceiveProps (nextProps) {
    // Request premissions only if the user has logged in.
    const { loggedIn } = nextProps
    if (loggedIn) {
      console.log('Requesting push notification permissions.')
      PushNotification.requestPermissions()
    }
  }

  // fires when the user presses the login button
  handlePressLogin () {
    const { navigator } = this.props
    const route = Routes.LoginScreen
    navigator.push(route)
  }

  // fires when the user presses the logout button
  handlePressLogout () {
    const { dispatch } = this.props
    dispatch(Actions.logout())
  }

  // fires when we tap the rocket!
  handlePressRocket () {
    const {dispatch} = this.props
    dispatch(Actions.requestTemperature('Boise'))
  }

  // fires when tap send
  handlePressSend () {
    const {dispatch} = this.props
    dispatch(Actions.requestTemperature('Toronto'))
  }

  // fires when tap star
  handlePressStar () {
    const {dispatch} = this.props
    dispatch(Actions.requestTemperature('New Orleans'))
  }

  renderLoginButton () {
    return (
      <View style={styles.loginBox}>
        <TouchableOpacity onPress={this.handlePressLogin}>
          <View style={styles.loginButton}>
            <Text style={styles.loginText}>{I18n.t('signIn')}</Text>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  renderLogoutButton () {
    return (
      <View style={styles.loginBox}>
        <TouchableOpacity onPress={this.handlePressLogout}>
          <View style={styles.loginButton}>
            <Text style={styles.loginText}>{I18n.t('logOut')}</Text>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  render () {
    const { loggedIn, temperature, city } = this.props
    return (
      <ScrollView style={styles.screenContainer}>
        <Text style={styles.componentLabel}>{I18n.t('loginLogoutExampleTitle')}</Text>
        {loggedIn ? this.renderLogoutButton() : this.renderLoginButton()}
        <Text style={styles.componentLabel}>{I18n.t('progressiveImageComponent')}</Text>
        <ProgressiveImage
          style={styles.progressiveImage}
          defaultSource={Images.logo}
          source='https://upload.wikimedia.org/wikipedia/commons/c/cc/ESC_large_ISS022_ISS022-E-11387-edit_01.JPG'
          thumbnail='http://i.imgur.com/eVAFUhj.png'
        />
        <View style={styles.groupContainer}>
          <ProgressiveImage
            style={styles.smallImage}
            defaultSource={Images.logo}
            source='http://imgur.com/3BaDWGT.png'
            thumbnail='http://imgur.com/3BaDWGT.png'
          />
          <ProgressiveImage
            style={styles.mediumImage}
            defaultSource={Images.logo}
            source='http://imgur.com/HWcqUJJ.jpg'
            thumbnail='http://imgur.com/M07ucqg.png'
          />
          <ProgressiveImage
            style={styles.largeImage}
            defaultSource={Images.logo}
            source='http://imgur.com/LgSAS60.jpg'
            thumbnail='http://imgur.com/l2QQs2R.png'
          />
        </View>
        <Text style={styles.componentLabel}>{I18n.t('api')}: {city}</Text>
        <Text style={styles.temperature}>{temperature && `${temperature} ${I18n.t('tempIndicator')}`}</Text>
        <Text style={styles.componentLabel}>{I18n.t('rnVectorIcons')}</Text>
        <View style={styles.groupContainer}>
          <TouchableOpacity onPress={this.handlePressRocket}>
            <Icon name='rocket' size={Metrics.icons.medium} color={Colors.error} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.handlePressSend}>
            <Icon name='send' size={Metrics.icons.medium} color={Colors.error} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.handlePressStar}>
            <Icon name='star' size={Metrics.icons.medium} color={Colors.error} />
          </TouchableOpacity>
          <Icon name='trophy' size={Metrics.icons.medium} color={Colors.error} />
          <Icon name='warning' size={Metrics.icons.medium} color={Colors.error} />
        </View>
        <View style={styles.groupContainer}>
          <Icon.Button name='facebook' style={styles.facebookButton} backgroundColor={Colors.facebook} onPress={() => window.alert('Facebook')}>
            {I18n.t('loginWithFacebook')}
          </Icon.Button>
        </View>
        <Text style={styles.componentLabel}>{I18n.t('rnAnimatable')}</Text>
        <View style={styles.groupContainer}>
          <Animatable.Text animation='fadeIn' iterationCount='infinite' direction='alternate'>{I18n.t('rnAnimatable')}</Animatable.Text>
          <Animatable.Image animation='pulse' iterationCount='infinite' source={Images.logo} />
          <Animatable.View animation='jello' iterationCount='infinite'>
            <Icon name='cab' size={Metrics.icons.medium} />
          </Animatable.View>
        </View>
      </ScrollView>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    loggedIn: state.login.username !== null,
    temperature: state.weather.temperature,
    city: state.weather.city
  }
}

export default connect(mapStateToProps)(AllComponentsScreen)
<commit_msg>Set temp container height to prevent collapse on icon press<commit_after>// An All Components Screen is a great way to dev and quick-test components
import React, { View, ScrollView, Text, TouchableOpacity, PropTypes } from 'react-native'
import { connect } from 'react-redux'
import styles from './Styles/AllComponentsScreenStyle'
import ProgressiveImage from '../Components/ProgressiveImage'
import { Colors, Images, Metrics } from '../Themes'
import Actions from '../Actions/Creators'
import Routes from '../Navigation/Routes'
// external libs
import Icon from 'react-native-vector-icons/FontAwesome'
import Animatable from 'react-native-animatable'
import PushNotification from 'react-native-push-notification'

// I18n
import I18n from '../I18n/I18n.js'

export default class AllComponentsScreen extends React.Component {

  constructor (props) {
    super(props)
    this.state = {}
    this.handlePressLogin = this.handlePressLogin.bind(this)
    this.handlePressLogout = this.handlePressLogout.bind(this)
    this.handlePressRocket = this.handlePressRocket.bind(this)
    this.handlePressSend = this.handlePressSend.bind(this)
    this.handlePressStar = this.handlePressStar.bind(this)
  }

  static propTypes = {
    navigator: PropTypes.object.isRequired,
    loggedIn: PropTypes.bool,
    dispatch: PropTypes.func,
    temperature: PropTypes.number,
    city: PropTypes.string
  };

  componentWillMount () {
    this.props.navigator.state.tapHamburger = () => {
      this.props.navigator.drawer.toggle()
    }
  }

  componentWillReceiveProps (nextProps) {
    // Request premissions only if the user has logged in.
    const { loggedIn } = nextProps
    if (loggedIn) {
      console.log('Requesting push notification permissions.')
      PushNotification.requestPermissions()
    }
  }

  // fires when the user presses the login button
  handlePressLogin () {
    const { navigator } = this.props
    const route = Routes.LoginScreen
    navigator.push(route)
  }

  // fires when the user presses the logout button
  handlePressLogout () {
    const { dispatch } = this.props
    dispatch(Actions.logout())
  }

  // fires when we tap the rocket!
  handlePressRocket () {
    const {dispatch} = this.props
    dispatch(Actions.requestTemperature('Boise'))
  }

  // fires when tap send
  handlePressSend () {
    const {dispatch} = this.props
    dispatch(Actions.requestTemperature('Toronto'))
  }

  // fires when tap star
  handlePressStar () {
    const {dispatch} = this.props
    dispatch(Actions.requestTemperature('New Orleans'))
  }

  renderLoginButton () {
    return (
      <View style={styles.loginBox}>
        <TouchableOpacity onPress={this.handlePressLogin}>
          <View style={styles.loginButton}>
            <Text style={styles.loginText}>{I18n.t('signIn')}</Text>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  renderLogoutButton () {
    return (
      <View style={styles.loginBox}>
        <TouchableOpacity onPress={this.handlePressLogout}>
          <View style={styles.loginButton}>
            <Text style={styles.loginText}>{I18n.t('logOut')}</Text>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  render () {
    const { loggedIn, temperature, city } = this.props
    return (
      <ScrollView style={styles.screenContainer}>
        <Text style={styles.componentLabel}>{I18n.t('loginLogoutExampleTitle')}</Text>
        {loggedIn ? this.renderLogoutButton() : this.renderLoginButton()}
        <Text style={styles.componentLabel}>{I18n.t('progressiveImageComponent')}</Text>
        <ProgressiveImage
          style={styles.progressiveImage}
          defaultSource={Images.logo}
          source='https://upload.wikimedia.org/wikipedia/commons/c/cc/ESC_large_ISS022_ISS022-E-11387-edit_01.JPG'
          thumbnail='http://i.imgur.com/eVAFUhj.png'
        />
        <View style={styles.groupContainer}>
          <ProgressiveImage
            style={styles.smallImage}
            defaultSource={Images.logo}
            source='http://imgur.com/3BaDWGT.png'
            thumbnail='http://imgur.com/3BaDWGT.png'
          />
          <ProgressiveImage
            style={styles.mediumImage}
            defaultSource={Images.logo}
            source='http://imgur.com/HWcqUJJ.jpg'
            thumbnail='http://imgur.com/M07ucqg.png'
          />
          <ProgressiveImage
            style={styles.largeImage}
            defaultSource={Images.logo}
            source='http://imgur.com/LgSAS60.jpg'
            thumbnail='http://imgur.com/l2QQs2R.png'
          />
        </View>
        <Text style={styles.componentLabel}>{I18n.t('api')}: {city}</Text>
        <View style={[styles.groupContainer, {height: 50}]}>
          <Text style={styles.temperature}>{temperature && `${temperature} ${I18n.t('tempIndicator')}`}</Text>
        </View>
        <Text style={styles.componentLabel}>{I18n.t('rnVectorIcons')}</Text>
        <View style={styles.groupContainer}>
          <TouchableOpacity onPress={this.handlePressRocket}>
            <Icon name='rocket' size={Metrics.icons.medium} color={Colors.error} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.handlePressSend}>
            <Icon name='send' size={Metrics.icons.medium} color={Colors.error} />
          </TouchableOpacity>
          <TouchableOpacity onPress={this.handlePressStar}>
            <Icon name='star' size={Metrics.icons.medium} color={Colors.error} />
          </TouchableOpacity>
          <Icon name='trophy' size={Metrics.icons.medium} color={Colors.error} />
          <Icon name='warning' size={Metrics.icons.medium} color={Colors.error} />
        </View>
        <View style={styles.groupContainer}>
          <Icon.Button name='facebook' style={styles.facebookButton} backgroundColor={Colors.facebook} onPress={() => window.alert('Facebook')}>
            {I18n.t('loginWithFacebook')}
          </Icon.Button>
        </View>
        <Text style={styles.componentLabel}>{I18n.t('rnAnimatable')}</Text>
        <View style={styles.groupContainer}>
          <Animatable.Text animation='fadeIn' iterationCount='infinite' direction='alternate'>{I18n.t('rnAnimatable')}</Animatable.Text>
          <Animatable.Image animation='pulse' iterationCount='infinite' source={Images.logo} />
          <Animatable.View animation='jello' iterationCount='infinite'>
            <Icon name='cab' size={Metrics.icons.medium} />
          </Animatable.View>
        </View>
      </ScrollView>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    loggedIn: state.login.username !== null,
    temperature: state.weather.temperature,
    city: state.weather.city
  }
}

export default connect(mapStateToProps)(AllComponentsScreen)
<|endoftext|>


<commit_before>/* eslint eqeqeq: 0, quotes: 0, no-unused-vars: [2, "local"] */

var bbsReader = function(){
	"use strict";

	var quoteData = {
		"&": "&",
		"<": "<",
		">": ">"
	};

	var quote = function(text){
		var key;
		for(key in quoteData){
			text = text.split(key).join(quoteData[key]);
		}
		return text;
	};

	var className = function(c){
		return "c" + c.fg + c.light + " b" + c.bg;
	};

	var extract = function(c){
		var i, ct = {light: null, fg: null, bg: null};
		c = c.split(";");
		for(i = 0; i < c.length; i++){
			if(c[i] == 0){
				ct = {light: 0, fg: 37, bg: 40};
			}else if (c[i] == 1){
				ct.light = 1;
			}else if (c[i] < 40){
				ct.fg = c[i];
			}else if (c[i] < 50){
				ct.bg = c[i];
			}
		}
		return ct;
	};

	var apply = function(colorState, ctrl){
		var newState = extract(ctrl), key, state = {};
		for(key in newState){
			if(newState[key] !== null){
				state[key] = newState[key];
			}else{
				state[key] = colorState[key];
			}
		}
		return state;
	};

	var parseLine = function(lineText){
		var m = null,
			p = 0,
			text = "",
			RE = /\x1B\[([\d\;]*?)m/g,
			colorState = {
				light: 0,
				fg: 37,
				bg: 40
			};

		while ((m = RE.exec(lineText))) {
			colorState = apply(colorState, m[1]);
			text += quote(lineText.substring(p, m.index));
			text += '';
			p = RE.lastIndex;
		}
		text += quote(lineText.substring(p)) + "";
		return text;
	};

	var init = function(source){
		source = source.replace(/ /g, "\u00A0");
		source = source.replace(/\?\[[\d\;]*?m/g, "_"); //掉字
		var lines = source.split(/\r?\n/);
		var i;
		for (i = 0; i < lines.length; i++) {
			lines[i] = "
" + parseLine(lines[i]) + "
";
		}
		return lines.join("");
	};

	return init;
}();
<commit_msg>Remove trailing space<commit_after>/* eslint eqeqeq: 0, quotes: 0, no-unused-vars: [2, "local"] */

var bbsReader = function(){
	"use strict";

	var quoteData = {
		"&": "&",
		"<": "<",
		">": ">"
	};

	var quote = function(text){
		var key;
		for(key in quoteData){
			text = text.split(key).join(quoteData[key]);
		}
		return text;
	};

	var className = function(c){
		return "c" + c.fg + c.light + " b" + c.bg;
	};

	var extract = function(c){
		var i, ct = {light: null, fg: null, bg: null};
		c = c.split(";");
		for(i = 0; i < c.length; i++){
			if(c[i] == 0){
				ct = {light: 0, fg: 37, bg: 40};
			}else if (c[i] == 1){
				ct.light = 1;
			}else if (c[i] < 40){
				ct.fg = c[i];
			}else if (c[i] < 50){
				ct.bg = c[i];
			}
		}
		return ct;
	};

	var apply = function(colorState, ctrl){
		var newState = extract(ctrl), key, state = {};
		for(key in newState){
			if(newState[key] !== null){
				state[key] = newState[key];
			}else{
				state[key] = colorState[key];
			}
		}
		return state;
	};

	var parseLine = function(lineText){
		var m = null,
			p = 0,
			text = "",
			RE = /\x1B\[([\d\;]*?)m/g,
			colorState = {
				light: 0,
				fg: 37,
				bg: 40
			};

		while ((m = RE.exec(lineText))) {
			colorState = apply(colorState, m[1]);
			text += quote(lineText.substring(p, m.index));
			text += '';
			p = RE.lastIndex;
		}
		text += quote(lineText.substring(p)) + "";
		return text;
	};

	var init = function(source){
		source = source.replace(/ /g, "\u00A0");
		source = source.replace(/\?\[[\d\;]*?m/g, "_"); //掉字
		var lines = source.split(/\r?\n/);
		var i;
		for (i = 0; i < lines.length; i++) {
			lines[i] = "
" + parseLine(lines[i]) + "
";
		}
		return lines.join("");
	};

	return init;
}();
<|endoftext|>


<commit_before>asynctest(
  'Matrix Keying Test',

  [
    'ephox.agar.api.FocusTools',
    'ephox.agar.api.Keyboard',
    'ephox.agar.api.Keys',
    'ephox.alloy.api.GuiFactory',
    'ephox.alloy.construct.EventHandler',
    'ephox.alloy.test.GuiSetup',
    'ephox.alloy.test.NavigationUtils',
    'ephox.boulder.api.Objects',
    'ephox.compass.Arr'
  ],

  function (FocusTools, Keyboard, Keys, GuiFactory, EventHandler, GuiSetup, NavigationUtils, Objects, Arr) {
    var success = arguments[arguments.length - 2];
    var failure = arguments[arguments.length - 1];

    var cells = [
      'c01', 'c02', 'c03', 'c04', 'c05', 'c06',
      'c07', 'c08', 'c09', 'c10', 'c11', 'c12',
      'c13', 'c14', 'c15', 'c16', 'c17', 'c18',
      'c19', 'c20', 'c21'
    ];

    GuiSetup.setup(function (store, doc, body) {
      var rows = Arr.chunk(cells, 6);

      var item = function (classes) {
        return {
          uiType: 'custom',
          dom: {
            tag: 'span',
            styles: {
              display: 'inline-block',
              width: '20px',
              height: '20px',
              margin: '1px',
              border: '1px solid black'
            },
            classes: [ 'cell' ].concat(classes)
          },
          events: {
            'alloy.execute': EventHandler.nu({
              run: store.adder('item.execute: ' + classes.join(','))
            })
          },
          focusing: true
        };
      };

      return GuiFactory.build({
        uiType: 'custom',
        dom: {
          tag: 'div',
          classes: [ 'matrix-keying-test'],
          styles: {
            background: 'white',
            width: '150px',
            height: '200px'
          }
        },
        uid: 'custom-uid',
        keying: {
          mode: 'matrix',
          selectors: {
            row: '.row',
            cell: '.cell'
          }
        },
        // 4 x 6 grid size
        components: Arr.map(rows, function (row) {
          return {
            uiType: 'custom',
            dom: {
              tag: 'span',
              classes: [ 'row' ]
            },
            components: Arr.map(row, function (c) {
              return item([ c ]);
            })
          };
        })
      });

    }, function (doc, body, gui, component, store) {

      var targets = Objects.wrapAll(
        Arr.map(cells, function (sq) {
          return {
            key: sq,
            value: {
              label: sq,
              selector: '.' + sq
            }
          };
        })
      );

      return [
        GuiSetup.mSetupKeyLogger(body),
        FocusTools.sSetFocus('Initial focus', gui.element(), '.c11'),
        NavigationUtils.sequence(
          doc,
          Keys.down(),
          {},
          [
            targets.c17,
            targets.c21,
            targets.c03,
            targets.c09,
            targets.c15,
            targets.c21,
            targets.c03
          ]
        ),
        NavigationUtils.sequence(
          doc,
          Keys.left(),
          {  },
          [
            targets.c02,
            targets.c01,
            targets.c06,
            targets.c05,
            targets.c04,
            targets.c03,
            targets.c02,
            targets.c01,
            targets.c06
          ]
        ),
        NavigationUtils.sequence(
          doc,
          Keys.up(),
          {  },
          [
            targets.c21,
            targets.c15,
            targets.c09,
            targets.c03,
            targets.c21,
            targets.c15,
            targets.c09,
            targets.c03,
            targets.c21
          ]
        ),
        NavigationUtils.sequence(
          doc,
          Keys.right(),
          {  },
          [
            targets.c19,
            targets.c20,
            targets.c21,
            targets.c19,
            targets.c20,
            targets.c21
          ]
        ),

        NavigationUtils.sequence(
          doc,
          Keys.left(),
          {  },
          [
            targets.c20,
            targets.c19,
            targets.c21,
            targets.c20,
            targets.c19,
            targets.c21
          ]
        ),

        // Test execute
        Keyboard.sKeydown(doc, Keys.enter(), {}),
        store.sAssertEq(
          'Execute should have c21',
          [ 'item.execute: c21' ]
        ),

        GuiSetup.mTeardownKeyLogger(body, [ ])
      ];
    }, function () {
      success();
    }, failure);
  }
);<commit_msg>VAN-44-wheel-hackery-apis-2: Matrix key test<commit_after>asynctest(
  'Matrix Keying Test',

  [
    'ephox.agar.api.FocusTools',
    'ephox.agar.api.Keyboard',
    'ephox.agar.api.Keys',
    'ephox.alloy.api.GuiFactory',
    'ephox.alloy.construct.EventHandler',
    'ephox.alloy.test.GuiSetup',
    'ephox.alloy.test.NavigationUtils',
    'ephox.boulder.api.Objects',
    'ephox.compass.Arr'
  ],

  function (FocusTools, Keyboard, Keys, GuiFactory, EventHandler, GuiSetup, NavigationUtils, Objects, Arr) {
    var success = arguments[arguments.length - 2];
    var failure = arguments[arguments.length - 1];

    var cells = [
      'c01', 'c02', 'c03', 'c04', 'c05', 'c06',
      'c07', 'c08', 'c09', 'c10', 'c11', 'c12',
      'c13', 'c14', 'c15', 'c16', 'c17', 'c18',
      'c19', 'c20', 'c21'
    ];

    GuiSetup.setup(function (store, doc, body) {
      var rows = Arr.chunk(cells, 6);

      var item = function (classes) {
        return {
          uiType: 'custom',
          dom: {
            tag: 'span',
            styles: {
              display: 'inline-block',
              width: '20px',
              height: '20px',
              margin: '1px',
              border: '1px solid black'
            },
            classes: [ 'cell' ].concat(classes)
          },
          events: {
            'alloy.execute': EventHandler.nu({
              run: store.adder('item.execute: ' + classes.join(','))
            })
          },
          behaviours: {
            focusing: true
          }
        };
      };

      return GuiFactory.build({
        uiType: 'custom',
        dom: {
          tag: 'div',
          classes: [ 'matrix-keying-test'],
          styles: {
            background: 'white',
            width: '150px',
            height: '200px'
          }
        },
        uid: 'custom-uid',
        behaviours: {
          keying: {
            mode: 'matrix',
            selectors: {
              row: '.row',
              cell: '.cell'
            }
          }
        },
        // 4 x 6 grid size
        components: Arr.map(rows, function (row) {
          return {
            uiType: 'custom',
            dom: {
              tag: 'span',
              classes: [ 'row' ]
            },
            components: Arr.map(row, function (c) {
              return item([ c ]);
            })
          };
        })
      });

    }, function (doc, body, gui, component, store) {

      var targets = Objects.wrapAll(
        Arr.map(cells, function (sq) {
          return {
            key: sq,
            value: {
              label: sq,
              selector: '.' + sq
            }
          };
        })
      );

      return [
        GuiSetup.mSetupKeyLogger(body),
        FocusTools.sSetFocus('Initial focus', gui.element(), '.c11'),
        NavigationUtils.sequence(
          doc,
          Keys.down(),
          {},
          [
            targets.c17,
            targets.c21,
            targets.c03,
            targets.c09,
            targets.c15,
            targets.c21,
            targets.c03
          ]
        ),
        NavigationUtils.sequence(
          doc,
          Keys.left(),
          {  },
          [
            targets.c02,
            targets.c01,
            targets.c06,
            targets.c05,
            targets.c04,
            targets.c03,
            targets.c02,
            targets.c01,
            targets.c06
          ]
        ),
        NavigationUtils.sequence(
          doc,
          Keys.up(),
          {  },
          [
            targets.c21,
            targets.c15,
            targets.c09,
            targets.c03,
            targets.c21,
            targets.c15,
            targets.c09,
            targets.c03,
            targets.c21
          ]
        ),
        NavigationUtils.sequence(
          doc,
          Keys.right(),
          {  },
          [
            targets.c19,
            targets.c20,
            targets.c21,
            targets.c19,
            targets.c20,
            targets.c21
          ]
        ),

        NavigationUtils.sequence(
          doc,
          Keys.left(),
          {  },
          [
            targets.c20,
            targets.c19,
            targets.c21,
            targets.c20,
            targets.c19,
            targets.c21
          ]
        ),

        // Test execute
        Keyboard.sKeydown(doc, Keys.enter(), {}),
        store.sAssertEq(
          'Execute should have c21',
          [ 'item.execute: c21' ]
        ),

        GuiSetup.mTeardownKeyLogger(body, [ ])
      ];
    }, function () {
      success();
    }, failure);
  }
);<|endoftext|>


<commit_before>/* Beaconator js */
$(document).ready(function(){

	$option_area = $('#option_area');
	$new_options = $('#new_options');
	$add_option = $('#add_option');
	$beaconize = $('#beaconize');
	$reset = $('#reset');
	$results = $('#results');
	var num_options = 2;
	var options = [];

	// Hide results on page load
	$results.hide();

	// Adds a new option to the list
	$add_option.click(function(){

		// Increment counter
		num_options++;

		// Add preconfigured html to the page
		var opt = "
";
		opt +=       "Option " + num_options + "";
		opt +=       "<input type='button' id='clear" + num_options + "' class='clear' />";
		opt +=       "<input type='text' id='Option" + num_options + "' class='form-control' />";
		opt +=    "
";
		$new_options.append(opt);
	});

	$('.clear').click(funciton(){

		// Remove that option
	});

	$beaconize.click(function(){

		// Clear out array
		options = [];

		// Parse options into array
		for(var i = 0; i < num_options; i++){

			var option_id = "#Option" + i;

			options.push($option_area.find(option_id).value);
		}

		// Read beacon API

		// Convert hex to decimal

		// Perform modulo

		// Display results

		$results.show();
	});

	$reset.click(function(){

		// Shut. Down. Everything.
		for(var i = 0; i < num_options; i++){

			// Reset all option values
			var option_id = "#Option" + i;
			$(option_id).val("");
		}

		// Reset options
		num_options = 2;
		options = [];

		// Clear out added options
		$new_options.empty();

		// Hide results
		$results.hide();
	});
});<commit_msg>Improves funcitonality<commit_after>/* Beaconator js */
$(document).ready(function(){

	$option_area = $('#option_area');
	$new_options = $('#new_options');
	$add_option = $('#add_option');
	$beaconize = $('#beaconize');
	$reset = $('#reset');
	$results = $('#results');
	var num_options = 2;
	var options = [];

	// Hide results on page load
	$results.hide();

	// Adds a new option to the list
	$add_option.click(function(){

		// Increment counter
		num_options++;

		// Add preconfigured html to the page
		var opt = "
";
		opt +=       "Option " + num_options + "";
		opt +=       "<input type='button' id='clear" + num_options + "' class='clear' />";
		opt +=       "<input type='text' id='Option" + num_options + "' class='form-control' />";
		opt +=    "
";
		$new_options.append(opt);
	});

	$('.clear').click(function(){

		// Remove that option
	});

	$beaconize.click(function(){

		// Clear out array
		options = [];

		// Parse options into array
		for(var i = 0; i < num_options; i++){

			var option_id = "#Option" + i;

			options.push($option_area.find(option_id).value);
		}

		// Read beacon API

		// Convert hex to decimal

		// Perform modulo

		// Display results

		$results.show();
	});

	$reset.click(function(){

		// Shut. Down. Everything.
		for(var i = 0; i < num_options; i++){

			// Reset all option values
			var option_id = "#Option" + i;
			$(option_id).val("");
		}

		// Reset options
		num_options = 2;
		options = [];

		// Clear out added options
		$new_options.empty();

		// Hide results
		$results.hide();
	});
});<|endoftext|>


<commit_before>(function (window, angular, $, chrome, undefined) {
    'use strict';

    var CONTROLLER_ID = 'ConfigController';

    angular.module('powellDevTools').controller(CONTROLLER_ID,
        ['$scope', '$element', '$q', '$sce', '$timeout', '$interval', 'datacontextUtility',
            configControllerModule]);

    function configControllerModule($scope, $element, $q, $sce, $timeout, $interval, datacontextUtility) {
        return new ConfigController($scope, $element, $q, $sce, $timeout, $interval, datacontextUtility);
    }

    var ConfigController = function ($scope, $element, $q, $sce, $timeout, $interval, datacontextUtility) {
        var _this = this;

        /*****************
         * View variables
         *****************/
        $scope.configTemplateUrl = 'resources/html/ConfigController.html';
        $scope.config = {
            repoJsURL: datacontextUtility.get_repoJsURL(),
            defaultJsRepoState: datacontextUtility.get_defaultJsRepoState(),
            repoCssURL: datacontextUtility.get_repoCssURL(),
            defaultCssRepoState: datacontextUtility.get_defaultCssRepoState(),
            //devJsID: datacontextUtility.get_devJsID(),
            devCssID: datacontextUtility.get_devCssID(),
            //tenantJsID: datacontextUtility.get_tenantJsID(),
            defaultJsTenantState: datacontextUtility.get_defaultJsTenantState(),
            tenantCssID: datacontextUtility.get_tenantCssID(),
            defaultCssTenantState: datacontextUtility.get_defaultCssTenantState(),
            envID: datacontextUtility.get_envID(),
            themeID: datacontextUtility.get_themeID(),
            useThemeState: datacontextUtility.get_useThemeState(),
            sourceMode : datacontextUtility.get_sourceMode(),
            cdnJsMode : datacontextUtility.get_cdnJsMode(),
            cdnCssMode : datacontextUtility.get_cdnCssMode()
        };

        $scope.enableJsEmulation = datacontextUtility.isEnabled('script');
        $scope.enableCssEmulation = datacontextUtility.isEnabled('stylesheet');
        $scope.environments = datacontextUtility.ENVIRONMENTS;
        $scope.sourceModes = datacontextUtility.SOURCEMODES;
        $scope.cdnModes = datacontextUtility.CDNMODES;

        $scope.$watchCollection('config', function(newValues) {
            for (var value in newValues) {
                datacontextUtility.setLocalStorageValue(value, newValues[value]);
            }
            $scope.emulationSources = {
                css: datacontextUtility.get_cssSourceUrl('*.css'),
                js: datacontextUtility.get_jsSourceUrl()
            };
        });

        $scope.isPaneActive = function (paneId) {
            return paneId == datacontextUtility.get_activePane() ? 'active' : '';
        };

        $scope.setActivePane = function (paneId) {
            datacontextUtility.set_activePane(paneId);
        };

        $scope.switchChanged = function (sourceKind) {
            chrome.extension.sendRequest({ 'action': 'setEnabled', 'enabled': !datacontextUtility.isEnabled(sourceKind), 'sourceKind': sourceKind });
        };

        $scope.clearLocalStorage = function() {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {method: "powDevTools.clearStorage"}, function(storageResponse) {
                    chrome.tabs.reload(tabs[0].id, {bypassCache: true}, function(refreshResponse) {
                        console.log(storageResponse, refreshResponse);
                        chrome.notifications.create(null, {
                            type: "basic",
                            iconUrl: "icon128.png",
                            title: "Powell Dev Tools",
                            message: "Local storage, local session and browser cache cleared successfully"
                        });
                    });
                });
            });
        };
    };

})(window, window.angular, window.jQuery, window.chrome);<commit_msg>Fix ConfigController angular template url<commit_after>(function (window, angular, $, chrome, undefined) {
    'use strict';

    var CONTROLLER_ID = 'ConfigController';

    angular.module('powellDevTools').controller(CONTROLLER_ID,
        ['$scope', '$element', '$q', '$sce', '$timeout', '$interval', 'datacontextUtility',
            configControllerModule]);

    function configControllerModule($scope, $element, $q, $sce, $timeout, $interval, datacontextUtility) {
        return new ConfigController($scope, $element, $q, $sce, $timeout, $interval, datacontextUtility);
    }

    var ConfigController = function ($scope, $element, $q, $sce, $timeout, $interval, datacontextUtility) {
        var _this = this;

        /*****************
         * View variables
         *****************/
        $scope.configTemplateUrl = 'https://rawgit.com/Expertime/powell-developer-tools/master/resources/html/ConfigController.html';
        $scope.config = {
            repoJsURL: datacontextUtility.get_repoJsURL(),
            defaultJsRepoState: datacontextUtility.get_defaultJsRepoState(),
            repoCssURL: datacontextUtility.get_repoCssURL(),
            defaultCssRepoState: datacontextUtility.get_defaultCssRepoState(),
            //devJsID: datacontextUtility.get_devJsID(),
            devCssID: datacontextUtility.get_devCssID(),
            //tenantJsID: datacontextUtility.get_tenantJsID(),
            defaultJsTenantState: datacontextUtility.get_defaultJsTenantState(),
            tenantCssID: datacontextUtility.get_tenantCssID(),
            defaultCssTenantState: datacontextUtility.get_defaultCssTenantState(),
            envID: datacontextUtility.get_envID(),
            themeID: datacontextUtility.get_themeID(),
            useThemeState: datacontextUtility.get_useThemeState(),
            sourceMode : datacontextUtility.get_sourceMode(),
            cdnJsMode : datacontextUtility.get_cdnJsMode(),
            cdnCssMode : datacontextUtility.get_cdnCssMode()
        };

        $scope.enableJsEmulation = datacontextUtility.isEnabled('script');
        $scope.enableCssEmulation = datacontextUtility.isEnabled('stylesheet');
        $scope.environments = datacontextUtility.ENVIRONMENTS;
        $scope.sourceModes = datacontextUtility.SOURCEMODES;
        $scope.cdnModes = datacontextUtility.CDNMODES;

        $scope.$watchCollection('config', function(newValues) {
            for (var value in newValues) {
                datacontextUtility.setLocalStorageValue(value, newValues[value]);
            }
            $scope.emulationSources = {
                css: datacontextUtility.get_cssSourceUrl('*.css'),
                js: datacontextUtility.get_jsSourceUrl()
            };
        });

        $scope.isPaneActive = function (paneId) {
            return paneId == datacontextUtility.get_activePane() ? 'active' : '';
        };

        $scope.setActivePane = function (paneId) {
            datacontextUtility.set_activePane(paneId);
        };

        $scope.switchChanged = function (sourceKind) {
            chrome.extension.sendRequest({ 'action': 'setEnabled', 'enabled': !datacontextUtility.isEnabled(sourceKind), 'sourceKind': sourceKind });
        };

        $scope.clearLocalStorage = function() {
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {method: "powDevTools.clearStorage"}, function(storageResponse) {
                    chrome.tabs.reload(tabs[0].id, {bypassCache: true}, function(refreshResponse) {
                        console.log(storageResponse, refreshResponse);
                        chrome.notifications.create(null, {
                            type: "basic",
                            iconUrl: "icon128.png",
                            title: "Powell Dev Tools",
                            message: "Local storage, local session and browser cache cleared successfully"
                        });
                    });
                });
            });
        };
    };

})(window, window.angular, window.jQuery, window.chrome);<|endoftext|>


<commit_before>'use strict';

/**
 * The post processing step that steps through all currently indexed assets
 * and deletes every asset that was not indexed during this run of the update to
 * the index.
 */

const Q = require('q');
const es = require('../../collections-online/lib/services/elasticsearch');
const _ = require('lodash');

module.exports = function(state) {
  var activity = 'Post-processing to delete removed assets';

  console.log('\n=== ' + activity + ' ===');

  if (!['all', 'catalog', 'single'].includes(state.mode)) {
    console.log('Removed assets gets deleted only in "all", "catalog" or ' +
                '"single" mode.');
    return state;
  }

  var deletedAssetIds;
  if (state.mode === 'all' || state.mode === 'catalog') {
    deletedAssetIds = state.queries.reduce((deletedAssetIds, query) => {
      console.log('Indexed', query.indexedIds.length, 'assets and series from', query.catalogAlias);
      return deletedAssetIds.then(deletedAssetIds => {
        if (query.offset > 0) {
          console.log('Skipping a query that had a non-zero offset.');
          return deletedAssetIds;
        }
        // Scroll search for all assets in the catalog that was not indexed.
        return es.scrollSearch({
          'query': {
            'bool': {
              'must': {
                'match': {
                  'catalog.raw': query.catalogAlias
                }
              },
              'must_not': {
                'ids': {
                  'values': query.indexedIds
                }
              }
            }
          }
        }, function(deletedAsset) {
          deletedAssetIds.push(deletedAsset._id);
        }).then(function() {
          return deletedAssetIds;
        });
      });
    }, new Q([]));
  } else {
    deletedAssetIds = state.queries.reduce((deletedAssetIds, query) => {
      var assetIds = query.assetIds.map(assetId => {
        return query.catalogAlias + '-' + assetId;
      });
      var moreDeletedAssetIds = _.difference(assetIds, query.indexedIds);
      return _.union(deletedAssetIds, moreDeletedAssetIds);
    }, []);
  }

  return Q.when(deletedAssetIds).then(deletedAssetIds => {
    console.log('Deleting', deletedAssetIds.length, 'asset(s)');
    var actions = deletedAssetIds.map(deletedAssetId => {
      return {delete: {_id: deletedAssetId}};
    });
    if (actions.length > 0) {
      return es.bulk({
        index: state.context.index,
        type: 'asset',
        body: actions
      });
    }
  }).then(function() {
    return state;
  });
};
<commit_msg>Add special case for asset cleanup in `all` indexings, remove series from cleaned up assets in all other cases<commit_after>'use strict';

/**
 * The post processing step that steps through all currently indexed assets
 * and deletes every asset that was not indexed during this run of the update to
 * the index.
 */

const Q = require('q');
const es = require('../../collections-online/lib/services/elasticsearch');
const _ = require('lodash');

module.exports = function(state) {
  var activity = 'Post-processing to delete removed assets';

  console.log('\n=== ' + activity + ' ===');

  if (!['all', 'catalog', 'single'].includes(state.mode)) {
    console.log('Removed assets gets deleted only in "all", "catalog" or ' +
                '"single" mode.');
    return state;
  }

  let deletedAssetIdsPromise;

  if (state.mode === 'all') {
    // In 'all' mode we just check the full list of items we indexed,
    // and remove all the assets and series in elasticsearch that are
    // not in our list -- we did a full re-index, so all of these can
    // be removed.
    const deletedAssetIds = [];

    const indexedIds = state.queries
      .filter((query) => query.offset === 0)
      .map((query) => query.indexedIds)
      .reduce((a, b) => a.concat(b), []);

    deletedAssetIdsPromise = es.scrollSearch({
      'query': {
        'bool': {
          'must_not': {
            'ids': {
              'values': indexedIds
            }
          }
        }
      }
    }, function(deletedEntry) {
      deletedAssetIds.push(deletedEntry._id);
    }).then(function() {
      return deletedAssetIds;
    });
  }
  else if (state.mode === 'catalog') {
    deletedAssetIdsPromise = state.queries.reduce((deletedAssetIdsPromise, query) => {
      console.log('Indexed', query.indexedIds.length, 'assets and series from', query.catalogAlias);
      return deletedAssetIdsPromise.then(deletedAssetIds => {
        if (query.offset > 0) {
          console.log('Skipping a query that had a non-zero offset.');
          return deletedAssetIds;
        }
        // Scroll search for all assets in the catalog that was not indexed.
        return es.scrollSearch({
          'query': {
            'bool': {
              'must': {
                'match': {
                  'catalog.raw': query.catalogAlias
                }
              },
              'must_not': {
                'ids': {
                  'values': query.indexedIds.filter((id) => !id.startsWith('series/')),
                }
              }
            }
          }
        }, function(deletedAsset) {
          deletedAssetIds.push(deletedAsset._id);
        }).then(function() {
          return deletedAssetIds;
        });
      });
    }, new Q([]));
  }
  else {
    const deletedAssetIds = state.queries.reduce((deletedAssetIds, query) => {
      const assetIds = query.assetIds
        .filter((assetId) => !assetId.startsWith('series/'))
        .map((assetId) => query.catalogAlias + '-' + assetId);

      const indexedAssetIds = query.indexedIds
        .filter((id) => !id.startsWith('series/'));

      const moreDeletedAssetIds = _.difference(assetIds, indexedAssetIds);
      return _.union(deletedAssetIds, moreDeletedAssetIds);
    }, []);

    deletedAssetIdsPromise = new Q(deletedAssetIds);
  }

  return Q.when(deletedAssetIdsPromise).then(deletedAssetIds => {
    console.log('Deleting', deletedAssetIds.length, 'asset(s)');
    var actions = deletedAssetIds.map(deletedAssetId => {
      return {delete: {_id: deletedAssetId}};
    });
    if (actions.length > 0) {
      return es.bulk({
        index: state.context.index,
        body: actions
      });
    }
  }).then(function() {
    return state;
  });
};
<|endoftext|>


<commit_before>import auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import history from '../history';

export default class Auth {
  userProfile;
  requestedScopes = 'openid profile read:messages write:messages';

  auth0 = new auth0.WebAuth({
    domain: AUTH_CONFIG.domain,
    clientID: AUTH_CONFIG.clientId,
    redirectUri: AUTH_CONFIG.callbackUrl,
    audience: AUTH_CONFIG.apiUrl,
    responseType: 'token id_token',
    scope: this.requestedScopes
  });

  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.userHasScopes = this.userHasScopes.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getProfile = this.getProfile.bind(this);
  }

  login() {
    this.auth0.authorize();
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
        history.replace('/home');
      } else if (err) {
        history.replace('/home');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  setSession(authResult) {
    // Set the time that the access token will expire at
    let expiresAt = JSON.stringify(
      authResult.expiresIn * 1000 + new Date().getTime()
    );
    // If there is a value on the `scope` param from the authResult,
    // use it to set scopes in the session for the user. Otherwise
    // use the scopes as requested. If no scopes were requested,
    // set it to nothing
    const scopes = authResult.scope || this.requestedScopes || '';

    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
    localStorage.setItem('scopes', JSON.stringify(scopes));
    // navigate to the home route
    history.replace('/home');
  }

  getAccessToken() {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
      throw new Error('No access token found');
    }
    return accessToken;
  }

  getProfile(cb) {
    let accessToken = this.getAccessToken();
    this.auth0.client.userInfo(accessToken, (err, profile) => {
      if (profile) {
        this.userProfile = profile;
      }
      cb(err, profile);
    });
  }

  logout() {
    // Clear access token and ID token from local storage
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    localStorage.removeItem('scopes');
    this.userProfile = null;
    // navigate to the home route
    history.replace('/home');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

  userHasScopes(scopes) {
    const grantedScopes = JSON.parse(localStorage.getItem('scopes')).split(' ');
    return scopes.every(scope => grantedScopes.includes(scope));
  }
}
<commit_msg>Fix blank screen when scopes not already defined (#42)<commit_after>import auth0 from 'auth0-js';
import { AUTH_CONFIG } from './auth0-variables';
import history from '../history';

export default class Auth {
  userProfile;
  requestedScopes = 'openid profile read:messages write:messages';

  auth0 = new auth0.WebAuth({
    domain: AUTH_CONFIG.domain,
    clientID: AUTH_CONFIG.clientId,
    redirectUri: AUTH_CONFIG.callbackUrl,
    audience: AUTH_CONFIG.apiUrl,
    responseType: 'token id_token',
    scope: this.requestedScopes
  });

  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.userHasScopes = this.userHasScopes.bind(this);
    this.getAccessToken = this.getAccessToken.bind(this);
    this.getProfile = this.getProfile.bind(this);
  }

  login() {
    this.auth0.authorize();
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken && authResult.idToken) {
        this.setSession(authResult);
        history.replace('/home');
      } else if (err) {
        history.replace('/home');
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  setSession(authResult) {
    // Set the time that the access token will expire at
    let expiresAt = JSON.stringify(
      authResult.expiresIn * 1000 + new Date().getTime()
    );
    // If there is a value on the `scope` param from the authResult,
    // use it to set scopes in the session for the user. Otherwise
    // use the scopes as requested. If no scopes were requested,
    // set it to nothing
    const scopes = authResult.scope || this.requestedScopes || '';

    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('id_token', authResult.idToken);
    localStorage.setItem('expires_at', expiresAt);
    localStorage.setItem('scopes', JSON.stringify(scopes));
    // navigate to the home route
    history.replace('/home');
  }

  getAccessToken() {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
      throw new Error('No access token found');
    }
    return accessToken;
  }

  getProfile(cb) {
    let accessToken = this.getAccessToken();
    this.auth0.client.userInfo(accessToken, (err, profile) => {
      if (profile) {
        this.userProfile = profile;
      }
      cb(err, profile);
    });
  }

  logout() {
    // Clear access token and ID token from local storage
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    localStorage.removeItem('expires_at');
    localStorage.removeItem('scopes');
    this.userProfile = null;
    // navigate to the home route
    history.replace('/home');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }

  userHasScopes(scopes) {
    const grantedScopes = (JSON.parse(localStorage.getItem('scopes')) || '').split(' ');
    return scopes.every(scope => grantedScopes.includes(scope));
  }
}
<|endoftext|>


<commit_before>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// TODO: ATTEMPT TO KILL THIS MODULE USING THIRD PARTY LIBRARIES WHEN IPYWIDGETS
// IS CONVERTED TO NODE COMMONJS.
"use strict";

var $ = require("./jquery");

/**
 * http://www.ietf.org/rfc/rfc4122.txt
 */
function uuid() {
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    return s.join("");
}

/**
 * Wrappable Error class
 *
 * The Error class doesn't actually act on `this`.  Instead it always
 * returns a new instance of Error.  Here we capture that instance so we
 * can apply it's properties to `this`.
 */
function WrappedError(message, error){
    var tmp = Error.apply(this, [message]);

    // Copy the properties of the error over to this.
    var properties = Object.getOwnPropertyNames(tmp);
    for (var i = 0; i < properties.length; i++) {
        this[properties[i]] = tmp[properties[i]];
    }

    // Keep a stack of the original error messages.
    if (error instanceof WrappedError) {
        this.error_stack = error.error_stack;
    } else {
        this.error_stack = [error];
    }
    this.error_stack.push(tmp);

    return this;
}
WrappedError.prototype = Object.create(Error.prototype, {});

/**
 * Tries to load a class
 *
 * Tries to load a class from a module using require.js, if a module
 * is specified, otherwise tries to load a class from the global
 * registry, if the global registry is provided.
 */
function loadClass(class_name, module_name, registry) {
    return new Promise(function(resolve, reject) {

        // Try loading the view module using require.js
        if (module_name) {

            // If the module is jupyter-js-widgets, we can just self import.
            var modulePromise;
            if (module_name === 'jupyter-js-widgets') {
                modulePromise = Promise.resolve(require('../'));
            } else {
                modulePromise = new Promise(function(innerResolve, innerReject) {
                    window.require([module_name], function(module) {
                        innerResolve(module);
                    }, innerReject);
                });
            }

            modulePromise.then(function(module) {
                if (module[class_name] === undefined) {
                    reject(new Error('Class '+class_name+' not found in module '+module_name));
                } else {
                    resolve(module[class_name]);
                }
            });
        } else {
            if (registry && registry[class_name]) {
                resolve(registry[class_name]);
            } else {
                reject(new Error('Class '+class_name+' not found in registry '));
            }
        }
    });
}

/**
 * Resolve a promiseful dictionary.
 * Returns a single Promise.
 */
function resolvePromisesDict(d) {
    var keys = Object.keys(d);
    var values = [];
    keys.forEach(function(key) {
        values.push(d[key]);
    });
    return Promise.all(values).then(function(v) {
        d = {};
        for(var i=0; i<keys.length; i++) {
            d[keys[i]] = v[i];
        }
        return d;
    });
}

/**
 * Creates a wrappable Promise rejection function.
 *
 * Creates a function that returns a Promise.reject with a new WrappedError
 * that has the provided message and wraps the original error that
 * caused the promise to reject.
 */
function reject(message, log) {
    return function promiseRejection(error) {
        var wrapped_error = new WrappedError(message, error);
        if (log) console.error(wrapped_error);
        return Promise.reject(wrapped_error);
    };
}

/**
 * Apply MathJax rendering to an element, and optionally set its text
 *
 * If MathJax is not available, make no changes.
 *
 * Returns the output any number of typeset elements, or undefined if
 * MathJax was not available.
 *
 * Parameters
 * ----------
 * element: Node, NodeList, or jQuery selection
 * text: option string
 */
function typeset(element, text) {
    var $el = element.jquery ? element : $(element);
    if(arguments.length > 1){
        $el.text(text);
    }
    if(!window.MathJax){
        return;
    }
    return $el.map(function(){
        // MathJax takes a DOM node: $.map makes `this` the context
        return MathJax.Hub.Queue(["Typeset", MathJax.Hub, this]);
    });
}

/**
 * escape text to HTML
 */
var escape_html = function (text) {
    return $("<div/>").text(text).html();
};

module.exports = {
    uuid: uuid,
    WrappedError: WrappedError,
    loadClass: loadClass,
    resolvePromisesDict: resolvePromisesDict,
    reject: reject,
    typeset: typeset,
    escape_html: escape_html
};
<commit_msg>Update typeset function to remove jQuery<commit_after>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

// TODO: ATTEMPT TO KILL THIS MODULE USING THIRD PARTY LIBRARIES WHEN IPYWIDGETS
// IS CONVERTED TO NODE COMMONJS.
"use strict";

var $ = require("./jquery");

/**
 * http://www.ietf.org/rfc/rfc4122.txt
 */
function uuid() {
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    return s.join("");
}

/**
 * Wrappable Error class
 *
 * The Error class doesn't actually act on `this`.  Instead it always
 * returns a new instance of Error.  Here we capture that instance so we
 * can apply it's properties to `this`.
 */
function WrappedError(message, error){
    var tmp = Error.apply(this, [message]);

    // Copy the properties of the error over to this.
    var properties = Object.getOwnPropertyNames(tmp);
    for (var i = 0; i < properties.length; i++) {
        this[properties[i]] = tmp[properties[i]];
    }

    // Keep a stack of the original error messages.
    if (error instanceof WrappedError) {
        this.error_stack = error.error_stack;
    } else {
        this.error_stack = [error];
    }
    this.error_stack.push(tmp);

    return this;
}
WrappedError.prototype = Object.create(Error.prototype, {});

/**
 * Tries to load a class
 *
 * Tries to load a class from a module using require.js, if a module
 * is specified, otherwise tries to load a class from the global
 * registry, if the global registry is provided.
 */
function loadClass(class_name, module_name, registry) {
    return new Promise(function(resolve, reject) {

        // Try loading the view module using require.js
        if (module_name) {

            // If the module is jupyter-js-widgets, we can just self import.
            var modulePromise;
            if (module_name === 'jupyter-js-widgets') {
                modulePromise = Promise.resolve(require('../'));
            } else {
                modulePromise = new Promise(function(innerResolve, innerReject) {
                    window.require([module_name], function(module) {
                        innerResolve(module);
                    }, innerReject);
                });
            }

            modulePromise.then(function(module) {
                if (module[class_name] === undefined) {
                    reject(new Error('Class '+class_name+' not found in module '+module_name));
                } else {
                    resolve(module[class_name]);
                }
            });
        } else {
            if (registry && registry[class_name]) {
                resolve(registry[class_name]);
            } else {
                reject(new Error('Class '+class_name+' not found in registry '));
            }
        }
    });
}

/**
 * Resolve a promiseful dictionary.
 * Returns a single Promise.
 */
function resolvePromisesDict(d) {
    var keys = Object.keys(d);
    var values = [];
    keys.forEach(function(key) {
        values.push(d[key]);
    });
    return Promise.all(values).then(function(v) {
        d = {};
        for(var i=0; i<keys.length; i++) {
            d[keys[i]] = v[i];
        }
        return d;
    });
}

/**
 * Creates a wrappable Promise rejection function.
 *
 * Creates a function that returns a Promise.reject with a new WrappedError
 * that has the provided message and wraps the original error that
 * caused the promise to reject.
 */
function reject(message, log) {
    return function promiseRejection(error) {
        var wrapped_error = new WrappedError(message, error);
        if (log) console.error(wrapped_error);
        return Promise.reject(wrapped_error);
    };
}

/**
 * Apply MathJax rendering to an element, and optionally set its text
 *
 * If MathJax is not available, make no changes.
 *
 * Returns the output any number of typeset elements as an array or undefined if
 * MathJax was not available.
 *
 * Parameters
 * ----------
 * element: Node, NodeList, or jQuery selection
 * text: option string
 */
function typeset(element, text) {
    if (arguments.length > 1) {
        if (element.length) {
            for (var i = 0; i < element.length; ++i) {
                var el = element[i];
                el.textContent = text;
            }
        } else {
            element.textContent = text;
        }
    }
    if (!window.MathJax) {
      return;
    }
    var output = [];
    if (element.length) {
        for (var i = 0; i < element.length; ++i) {
            var el = element[i];
            output.push(MathJax.Hub.Queue(['Typeset', MathJax.Hub, el]));
        }
    } else {
        output.push(MathJax.Hub.Queue(['Typeset', MathJax.Hub, element]));
    }
    return output;
}

/**
 * escape text to HTML
 */
var escape_html = function (text) {
    return $("<div/>").text(text).html();
};

module.exports = {
    uuid: uuid,
    WrappedError: WrappedError,
    loadClass: loadClass,
    resolvePromisesDict: resolvePromisesDict,
    reject: reject,
    typeset: typeset,
    escape_html: escape_html
};
<|endoftext|>


<commit_before>const argv = require('yargs').argv
const webpack = require('webpack')
const cssnano = require('cssnano')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const project = require('./project.config')
const debug = require('debug')('app:config:webpack')

const __DEV__ = project.globals.__DEV__
const __PROD__ = project.globals.__PROD__
const __TEST__ = project.globals.__TEST__

debug('Creating configuration.')
const webpackConfig = {
  name    : 'client',
  target  : 'web',
  devtool : project.compiler_devtool,
  resolve : {
    root       : project.paths.client(),
    extensions : ['', '.js', '.jsx', '.json']
  },
  module : {}
}
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY = project.paths.client('main.js')

webpackConfig.entry = {
  app : __DEV__
    ? [APP_ENTRY].concat(`webpack-hot-middleware/client?path=${project.compiler_public_path}__webpack_hmr`)
    : [APP_ENTRY],
  vendor : project.compiler_vendors
}

// ------------------------------------
// Bundle Output
// ------------------------------------

webpackConfig.output = {
  // filename   : `[name].[${project.compiler_hash_type}].js`,
  filename   : `[name].js`,
  path       : project.paths.dist(),
  publicPath : project.compiler_public_path
}

// ------------------------------------
// Externals
// ------------------------------------
webpackConfig.externals = {}
webpackConfig.externals['react/lib/ExecutionEnvironment'] = true
webpackConfig.externals['react/lib/ReactContext'] = true
webpackConfig.externals['react/addons'] = true

// ------------------------------------
// Plugins
// ------------------------------------
webpackConfig.plugins = [
  new webpack.DefinePlugin(project.globals),
  new HtmlWebpackPlugin({
    template : project.paths.client('index.html'),
    hash     : false,
    favicon  : project.paths.public('favicon.ico'),
    filename : 'index.html',
    inject   : 'body',
    minify   : {
      collapseWhitespace : true
    }
  })
]

// Ensure that the compiler exits on errors during testing so that
// they do not get skipped and misreported.
if (__TEST__ && !argv.watch) {
  webpackConfig.plugins.push(function () {
    this.plugin('done', function (stats) {
      if (stats.compilation.errors.length) {
        // Pretend no assets were generated. This prevents the tests
        // from running making it clear that there were warnings.
        throw new Error(
          stats.compilation.errors.map(err => err.message || err)
        )
      }
    })
  })
}

if (__DEV__) {
  debug('Enabling plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
} else if (__PROD__) {
  debug('Enabling plugins for production (OccurenceOrder, Dedupe & UglifyJS).')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress : {
        unused    : true,
        dead_code : true,
        warnings  : false
      }
    })
  )
}

// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
  webpackConfig.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({
      names : ['vendor']
    })
  )
}

// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
  test    : /\.(js|jsx)$/,
  exclude : /node_modules/,
  loader  : 'babel',
  query   : project.compiler_babel
}, {
  test   : /\.json$/,
  loader : 'json'
}]

// ------------------------------------
// Style Loaders
// ------------------------------------
// We use cssnano with the postcss loader, so we tell
// css-loader not to duplicate minimization.
const BASE_CSS_LOADER = 'css?sourceMap&-minimize'

webpackConfig.module.loaders.push({
  test    : /\.scss$/,
  exclude : null,
  loaders : [
    'style',
    BASE_CSS_LOADER,
    'postcss',
    'sass?sourceMap'
  ]
})
webpackConfig.module.loaders.push({
  test    : /\.css$/,
  exclude : null,
  loaders : [
    'style',
    BASE_CSS_LOADER,
    'postcss'
  ]
})

webpackConfig.sassLoader = {
  includePaths : project.paths.client('styles')
}

webpackConfig.postcss = [
  require('lost'),
  cssnano({
    autoprefixer : {
      add      : true,
      remove   : true,
      browsers : ['last 2 versions']
    },
    discardComments : {
      removeAll : true
    },
    discardUnused : false,
    mergeIdents   : false,
    reduceIdents  : false,
    safe          : true,
    sourcemap     : true
  })
]

// File loaders
/* eslint-disable */
webpackConfig.module.loaders.push(
  { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
  { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
  { test: /\.otf(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
  { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
  { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
  { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' }
)
/* eslint-enable */

// ------------------------------------
// Finalize Configuration
// ------------------------------------
// when we don't know the public path (we know it only when HMR is enabled [in development]) we
// need to use the extractTextPlugin to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
if (!__DEV__) {
  debug('Applying ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter((loader) =>
    loader.loaders && loader.loaders.find((name) => /css/.test(name.split('?')[0]))
  ).forEach((loader) => {
    const first = loader.loaders[0]
    const rest = loader.loaders.slice(1)
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].css', {
      allChunks : true
    })
  )
}
module.exports = webpackConfig
<commit_msg>Change link to styles in webpack config<commit_after>const argv = require('yargs').argv
const webpack = require('webpack')
const cssnano = require('cssnano')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const project = require('./project.config')
const debug = require('debug')('app:config:webpack')

const __DEV__ = project.globals.__DEV__
const __PROD__ = project.globals.__PROD__
const __TEST__ = project.globals.__TEST__

debug('Creating configuration.')
const webpackConfig = {
  name    : 'client',
  target  : 'web',
  devtool : project.compiler_devtool,
  resolve : {
    root       : project.paths.client(),
    extensions : ['', '.js', '.jsx', '.json']
  },
  module : {}
}
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY = project.paths.client('main.js')

webpackConfig.entry = {
  app : __DEV__
    ? [APP_ENTRY].concat(`webpack-hot-middleware/client?path=${project.compiler_public_path}__webpack_hmr`)
    : [APP_ENTRY],
  vendor : project.compiler_vendors
}

// ------------------------------------
// Bundle Output
// ------------------------------------

webpackConfig.output = {
  // filename   : `[name].[${project.compiler_hash_type}].js`,
  filename   : `[name].js`,
  path       : project.paths.dist(),
  publicPath : project.compiler_public_path
}

// ------------------------------------
// Externals
// ------------------------------------
webpackConfig.externals = {}
webpackConfig.externals['react/lib/ExecutionEnvironment'] = true
webpackConfig.externals['react/lib/ReactContext'] = true
webpackConfig.externals['react/addons'] = true

// ------------------------------------
// Plugins
// ------------------------------------
webpackConfig.plugins = [
  new webpack.DefinePlugin(project.globals),
  new HtmlWebpackPlugin({
    template : project.paths.client('index.html'),
    hash     : false,
    favicon  : project.paths.public('favicon.ico'),
    filename : 'index.html',
    inject   : 'body',
    minify   : {
      collapseWhitespace : true
    }
  })
]

// Ensure that the compiler exits on errors during testing so that
// they do not get skipped and misreported.
if (__TEST__ && !argv.watch) {
  webpackConfig.plugins.push(function () {
    this.plugin('done', function (stats) {
      if (stats.compilation.errors.length) {
        // Pretend no assets were generated. This prevents the tests
        // from running making it clear that there were warnings.
        throw new Error(
          stats.compilation.errors.map(err => err.message || err)
        )
      }
    })
  })
}

if (__DEV__) {
  debug('Enabling plugins for live development (HMR, NoErrors).')
  webpackConfig.plugins.push(
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  )
} else if (__PROD__) {
  debug('Enabling plugins for production (OccurenceOrder, Dedupe & UglifyJS).')
  webpackConfig.plugins.push(
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compress : {
        unused    : true,
        dead_code : true,
        warnings  : false
      }
    })
  )
}

// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
  webpackConfig.plugins.push(
    new webpack.optimize.CommonsChunkPlugin({
      names : ['vendor']
    })
  )
}

// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
  test    : /\.(js|jsx)$/,
  exclude : /node_modules/,
  loader  : 'babel',
  query   : project.compiler_babel
}, {
  test   : /\.json$/,
  loader : 'json'
}]

// ------------------------------------
// Style Loaders
// ------------------------------------
// We use cssnano with the postcss loader, so we tell
// css-loader not to duplicate minimization.
const BASE_CSS_LOADER = 'css?sourceMap&-minimize'

webpackConfig.module.loaders.push({
  test    : /\.scss$/,
  exclude : null,
  loaders : [
    'style',
    BASE_CSS_LOADER,
    'postcss',
    'sass?sourceMap'
  ]
})
webpackConfig.module.loaders.push({
  test    : /\.css$/,
  exclude : null,
  loaders : [
    'style',
    BASE_CSS_LOADER,
    'postcss'
  ]
})

webpackConfig.sassLoader = {
  includePaths : project.paths.client('layouts/styles')
}

webpackConfig.postcss = [
  require('lost'),
  cssnano({
    autoprefixer : {
      add      : true,
      remove   : true,
      browsers : ['last 2 versions']
    },
    discardComments : {
      removeAll : true
    },
    discardUnused : false,
    mergeIdents   : false,
    reduceIdents  : false,
    safe          : true,
    sourcemap     : true
  })
]

// File loaders
/* eslint-disable */
webpackConfig.module.loaders.push(
  { test: /\.woff(\?.*)?$/,  loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
  { test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
  { test: /\.otf(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
  { test: /\.ttf(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
  { test: /\.eot(\?.*)?$/,   loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
  { test: /\.svg(\?.*)?$/,   loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
  { test: /\.(png|jpg)$/,    loader: 'url?limit=8192' }
)
/* eslint-enable */

// ------------------------------------
// Finalize Configuration
// ------------------------------------
// when we don't know the public path (we know it only when HMR is enabled [in development]) we
// need to use the extractTextPlugin to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
if (!__DEV__) {
  debug('Applying ExtractTextPlugin to CSS loaders.')
  webpackConfig.module.loaders.filter((loader) =>
    loader.loaders && loader.loaders.find((name) => /css/.test(name.split('?')[0]))
  ).forEach((loader) => {
    const first = loader.loaders[0]
    const rest = loader.loaders.slice(1)
    loader.loader = ExtractTextPlugin.extract(first, rest.join('!'))
    delete loader.loaders
  })

  webpackConfig.plugins.push(
    new ExtractTextPlugin('[name].css', {
      allChunks : true
    })
  )
}
module.exports = webpackConfig
<|endoftext|>


<commit_before>window.Rendxx = window.Rendxx || {};
window.Rendxx.Game = window.Rendxx.Game || {};
window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {};
window.Rendxx.Game.Ghost.WebWorker = window.Rendxx.Game.Ghost.WebWorker || {};

/**
 * WebWorker Wrapper
 */
(function (GAME) {
    var WEBWORKER = GAME.WebWorker || {};
    var SYSTEM = GAME.System || {};
    var Data = SYSTEM.Data;
    var Wrapper = function (root, core) {
        // data ----------------------------------------------------------
        var that = this,
            // components
            worker = null,
            fileLoader = null,
            root = root || '',
            // cache
            _mapData = null,
            _modelData = null,
            _playerData = null,
            // function map
            funcMap = {
                "send": function (para) {
                    var dat = undefined;
                    if (para) dat = para.dat;
                    if (that.send) that.send(dat);
                },
                "onSetuped": function (para) {
                    var setupData = undefined;
                    if (para) setupData = para.setupData;
                    if (that.onSetuped) that.onSetuped(setupData);
                },
                "onUpdated": function (para) {
                    var gameData = undefined;
                    if (para) gameData = para.gameData;
                    if (that.onUpdated) that.onUpdated(gameData);
                },
                "clientSetup": function (para) {
                    var targets = undefined;
                    var clientData = undefined;
                    if (para) {
                        targets = para.targets;
                        clientData = para.clientData;
                    }
                    if (that.clientSetup) that.clientSetup(targets, clientData);
                },
                "clientUpdate": function (para) {
                    var targets = undefined;
                    var clientData = undefined;
                    if (para) {
                        targets = para.targets;
                        clientData = para.clientData;
                    }
                    if (that.clientUpdate) that.clientUpdate(targets, clientData);
                },
                "onEnd": function (para) {
                    var endData = undefined;
                    if (para) endData = para.endData;
                    if (that.onEnd) that.onEnd(endData);
                }
            };

        // message -----------------------------------------------
        this.send = null;   // (code, content)

        this.receive = function (msg) {
            worker.postMessage({
                func: 'receive',
                para: {
                    msg: msg
                }
            });
        };

        this.action = function (clientId, dat) {
            worker.postMessage({
                func: 'action',
                para: {
                    clientId: clientId,
                    dat: dat
                }
            });
        };

        // callback ------------------------------------------
        this.onUpdated = null;      // (gameData)
        this.onSetuped = null;      // (setupData)
        this.clientSetup = null;    // (target, clientData)
        this.clientUpdate = null;   // (target, clientData)
        this.onEnd = null;          // (target, clientData)

        // update ---------------------------------------------
        this.reset = function (setupData, gameData) {
            worker.postMessage({
                func: 'reset',
                para: {
                    setupData: setupData,
                    gameData: gameData
                }
            });
        }

        this.setup = function (playerData, para) {
            _playerData = playerData;
            var mapName = para.map;
            if (Data.map.files[mapName] == null) throw new Error('Map can not be found.');
            fileLoader.loadMap(Data.map.files[mapName],
                function (data) {
                    _mapData = data;
                    onLoaded();
                },
                function (e) {
                    throw new Error('Map Loading Error: ' + e);
                });
        };

        // game ------------------------------------------------
        this.start = function () {
            worker.postMessage({
                func: 'start',
                para: {}
            });
        };

        this.end = function () {
            worker.postMessage({
                func: 'end',
                para: {}
            });
        };

        this.renew = function () {
            worker.postMessage({
                func: 'renew',
                para: {}
            });
        };

        this.pause = function () {
            worker.postMessage({
                func: 'pause',
                para: {}
            });
        };

        this.continue = function () {
            worker.postMessage({
                func: 'continue',
                para: {
                }
            });
        };

        // private method ------------------------------------------------
        var onLoaded = function () {
            if (_mapData == null || _modelData == null) return;
            worker.postMessage({
                func: 'setup',
                para: {
                    modelData: _modelData,
                    mapData: _mapData,
                    playerData: _playerData
                }
            });
        };

        var _setupLoader = function () {
            fileLoader = new SYSTEM.FileLoader(root);
            fileLoader.loadBasic(function (data) {
                _modelData = data;
                onLoaded();
            });
        };

        var _setupWebWorker = function () {
            worker = new Worker((root || "") + core);
            worker.onmessage = function (e) {
                if (e == null || e.data == null || e.data.func == null || !funcMap.hasOwnProperty(e.data.func)) return;
                funcMap[e.data.func](e.data.para);
            };
            worker.postMessage({
                func: 'init',
                para: {}
            });
        };

        var _init = function () {
            _setupLoader();
            _setupWebWorker();
        };
        _init();
    };

    /**
     * Create web worker
     */
    WEBWORKER.Create = function (root, core) {
        var wrapper = new Wrapper(root, core);
        return wrapper;
    };
})(window.Rendxx.Game.Ghost);<commit_msg>try add renew<commit_after>window.Rendxx = window.Rendxx || {};
window.Rendxx.Game = window.Rendxx.Game || {};
window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {};
window.Rendxx.Game.Ghost.WebWorker = window.Rendxx.Game.Ghost.WebWorker || {};

/**
 * WebWorker Wrapper
 */
(function (GAME) {
    var WEBWORKER = GAME.WebWorker || {};
    var SYSTEM = GAME.System || {};
    var Data = SYSTEM.Data;
    var Wrapper = function (root, core) {
        // data ----------------------------------------------------------
        var that = this,
            // components
            worker = null,
            fileLoader = null,
            root = root || '',
            // cache
            _mapData = null,
            _modelData = null,
            _playerData = null,
            // function map
            funcMap = {
                "send": function (para) {
                    var dat = undefined;
                    if (para) dat = para.dat;
                    if (that.send) that.send(dat);
                },
                "onSetuped": function (para) {
                    var setupData = undefined;
                    if (para) setupData = para.setupData;
                    if (that.onSetuped) that.onSetuped(setupData);
                },
                "onUpdated": function (para) {
                    var gameData = undefined;
                    if (para) gameData = para.gameData;
                    if (that.onUpdated) that.onUpdated(gameData);
                },
                "clientSetup": function (para) {
                    var targets = undefined;
                    var clientData = undefined;
                    if (para) {
                        targets = para.targets;
                        clientData = para.clientData;
                    }
                    if (that.clientSetup) that.clientSetup(targets, clientData);
                },
                "clientUpdate": function (para) {
                    var targets = undefined;
                    var clientData = undefined;
                    if (para) {
                        targets = para.targets;
                        clientData = para.clientData;
                    }
                    if (that.clientUpdate) that.clientUpdate(targets, clientData);
                },
                "onEnd": function (para) {
                    var endData = undefined;
                    if (para) endData = para.endData;
                    if (that.onEnd) that.onEnd(endData);
                }
            };

        // message -----------------------------------------------
        this.send = null;   // (code, content)

        this.receive = function (msg) {
            worker.postMessage({
                func: 'receive',
                para: {
                    msg: msg
                }
            });
        };

        this.action = function (clientId, dat) {
            worker.postMessage({
                func: 'action',
                para: {
                    clientId: clientId,
                    dat: dat
                }
            });
        };

        // callback ------------------------------------------
        this.onUpdated = null;      // (gameData)
        this.onSetuped = null;      // (setupData)
        this.clientSetup = null;    // (target, clientData)
        this.clientUpdate = null;   // (target, clientData)
        this.onEnd = null;          // (target, clientData)

        // update ---------------------------------------------
        this.reset = function (setupData, gameData) {
            worker.postMessage({
                func: 'reset',
                para: {
                    setupData: setupData,
                    gameData: gameData
                }
            });
        }

        this.setup = function (playerData, para) {
            _playerData = playerData;
            var mapName = para.map;
            if (Data.map.files[mapName] == null) throw new Error('Map can not be found.');
            fileLoader.loadMap(Data.map.files[mapName],
                function (data) {
                    _mapData = data;
                    onLoaded();
                },
                function (e) {
                    throw new Error('Map Loading Error: ' + e);
                });
        };

        // game ------------------------------------------------
        this.start = function () {
            worker.postMessage({
                func: 'start',
                para: {}
            });
        };

        this.end = function () {
            worker.postMessage({
                func: 'end',
                para: {}
            });
        };

        this.renew = function () {
            _setupWebWorker();
            //worker.postMessage({
            //    func: 'renew',
            //    para: {}
            //});
        };

        this.pause = function () {
            worker.postMessage({
                func: 'pause',
                para: {}
            });
        };

        this.continue = function () {
            worker.postMessage({
                func: 'continue',
                para: {
                }
            });
        };

        // private method ------------------------------------------------
        var onLoaded = function () {
            if (_mapData == null || _modelData == null) return;
            worker.postMessage({
                func: 'setup',
                para: {
                    modelData: _modelData,
                    mapData: _mapData,
                    playerData: _playerData
                }
            });
        };

        var _setupLoader = function () {
            fileLoader = new SYSTEM.FileLoader(root);
            fileLoader.loadBasic(function (data) {
                _modelData = data;
                onLoaded();
            });
        };

        var _setupWebWorker = function () {
            if (worker != null) worker.terminate();
            worker = new Worker((root || "") + core);
            worker.onmessage = function (e) {
                if (e == null || e.data == null || e.data.func == null || !funcMap.hasOwnProperty(e.data.func)) return;
                funcMap[e.data.func](e.data.para);
            };
            worker.postMessage({
                func: 'init',
                para: {}
            });
        };

        var _init = function () {
            _setupLoader();
            _setupWebWorker();
        };
        _init();
    };

    /**
     * Create web worker
     */
    WEBWORKER.Create = function (root, core) {
        var wrapper = new Wrapper(root, core);
        return wrapper;
    };
})(window.Rendxx.Game.Ghost);<|endoftext|>


<commit_before>$('div.news').hide()
<commit_msg>New github dotjs.<commit_after>//$('div.news').hide()
$('div.alert.issues_comment').hide()

$('div.alert.watch_started').css('background-color', '#eee');
<|endoftext|>