<commit_before>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
'use strict';

var React = require('react-native');
var {
  StyleSheet,
  Text,
  View,
  TouchableWithoutFeedback,
} = React;
var ToastAndroid = require('ToastAndroid');
var AccessibilityInfo = require('AccessibilityInfo');

var UIExplorerBlock = require('./UIExplorerBlock');
var UIExplorerPage = require('./UIExplorerPage');

var AccessibilityAndroidExample = React.createClass({

  statics: {
    title: 'Accessibility',
    description: 'Examples of using Accessibility API.',
  },

  getInitialState: function() {
    return {
      count: 0,
      talkbackEnabled: false,
    };
  },

   componentDidMount: function() {
    AccessibilityInfo.addEventListener(
      'change',
      this._handleTouchExplorationChange
    );
    AccessibilityInfo.fetch().done((enabled) => {
      this.setState({
        count: this.state.count,
        talkbackEnabled: enabled}); }
    );
  },

  componentWillUnmount: function() {
    AccessibilityInfo.removeEventListener(
      'change',
      this._handleTouchExplorationChange
    );
  },

  _handleTouchExplorationChange: function(isEnabled) {
    this.setState({
      count: this.state.count,
      talkbackEnabled: isEnabled,
    });
  },

  _showAccessibilityToast: function() {
    var text = 'TouchExploration is ' + (this.state.talkbackEnabled ? 'enabled' : 'disabled');
    ToastAndroid.show(text, ToastAndroid.SHORT);
  },

  _addOne: function() {
    this.setState({
      count: ++this.state.count,
      talkbackEnabled: this.state.talkbackEnabled,
    });
  },

  render: function() {
    return (
      <UIExplorerPage title={'Accessibility'}>

        <UIExplorerBlock title="Nonaccessible view with TextViews">
          <View>
            <Text style={{color: 'green',}}>
              This is
            </Text>
            <Text style={{color: 'blue'}}>
              nontouchable normal view.
            </Text>
          </View>
        </UIExplorerBlock>

        <UIExplorerBlock title="Accessible view with TextViews wihout label">
          <View accessible={true}>
            <Text style={{color: 'green',}}>
              This is
            </Text>
            <Text style={{color: 'blue'}}>
              nontouchable accessible view without label.
            </Text>
          </View>
        </UIExplorerBlock>

        <UIExplorerBlock title="Accessible view with TextViews with label">
          <View accessible={true}
            accessibilityLabel="I have label, so I read it instead of embedded text.">
            <Text style={{color: 'green',}}>
              This is
            </Text>
            <Text style={{color: 'blue'}}>
              nontouchable accessible view with label.
            </Text>
          </View>
        </UIExplorerBlock>

        <UIExplorerBlock title="Touchable with component type = button">
          <TouchableWithoutFeedback
            onPress={() => ToastAndroid.show('Toasts work by default', ToastAndroid.SHORT)}>
            <View style={styles.embedded} accessibilityComponentType="button">
              <Text>Click me</Text>
              <Text>Or not</Text>
            </View>
          </TouchableWithoutFeedback>
        </UIExplorerBlock>

        <UIExplorerBlock title="LiveRegion">
          <TouchableWithoutFeedback onPress={this._addOne}>
            <View style={styles.embedded} accessibilityComponentType="button">
              <Text>Click me</Text>
            </View>
          </TouchableWithoutFeedback>
          <Text accessibilityLiveRegion="polite">
            Clicked {this.state.count} times
          </Text>
        </UIExplorerBlock>

        <UIExplorerBlock title="Check if TouchExploration is enabled">
          <TouchableWithoutFeedback onPress={this._showAccessibilityToast}>
            <View style={styles.embedded}>
              <Text>
                Click to check TouchExploration
              </Text>
            </View>
          </TouchableWithoutFeedback>
        </UIExplorerBlock>

      </UIExplorerPage>
    );
  },
});

var styles = StyleSheet.create({
   embedded: {
    backgroundColor: 'yellow',
    padding:10,
  },
});

module.exports = AccessibilityAndroidExample;
<commit_msg>[ReactNative] add importantForAccessibility to accessibility sample app<commit_after>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
'use strict';

var React = require('react-native');
var {
  StyleSheet,
  Text,
  View,
  TouchableWithoutFeedback,
} = React;
var ToastAndroid = require('ToastAndroid');
var AccessibilityInfo = require('AccessibilityInfo');

var UIExplorerBlock = require('./UIExplorerBlock');
var UIExplorerPage = require('./UIExplorerPage');

var importantForAccessibilityValues = ['auto', 'yes', 'no', 'no-hide-descendants'];

var AccessibilityAndroidExample = React.createClass({

  statics: {
    title: 'Accessibility',
    description: 'Examples of using Accessibility API.',
  },

  getInitialState: function() {
    return {
      count: 0,
      talkbackEnabled: false,
      backgroundImportantForAcc: 0,
      forgroundImportantForAcc: 0,
    };
  },

   componentDidMount: function() {
    AccessibilityInfo.addEventListener(
      'change',
      this._handleTouchExplorationChange
    );
    AccessibilityInfo.fetch().done((enabled) => {
      this.setState({
        count: this.state.count,
        talkbackEnabled: enabled}); }
    );
  },

  componentWillUnmount: function() {
    AccessibilityInfo.removeEventListener(
      'change',
      this._handleTouchExplorationChange
    );
  },

  _handleTouchExplorationChange: function(isEnabled) {
    this.setState({
      count: this.state.count,
      talkbackEnabled: isEnabled,
    });
  },

  _showAccessibilityToast: function() {
    var text = 'TouchExploration is ' + (this.state.talkbackEnabled ? 'enabled' : 'disabled');
    ToastAndroid.show(text, ToastAndroid.SHORT);
  },

  _addOne: function() {
    this.setState({
      count: ++this.state.count,
      talkbackEnabled: this.state.talkbackEnabled,
    });
  },

  _changeBackgroundImportantForAcc: function() {
    this.setState({
      backgroundImportantForAcc: (this.state.backgroundImportantForAcc + 1) % 4,
    });
  },

  _changeForgroundImportantForAcc: function() {
    this.setState({
      forgroundImportantForAcc: (this.state.forgroundImportantForAcc + 1) % 4,
    });
  },

  render: function() {
    return (
      <UIExplorerPage title={'Accessibility'}>

        <UIExplorerBlock title="Nonaccessible view with TextViews">
          <View>
            <Text style={{color: 'green',}}>
              This is
            </Text>
            <Text style={{color: 'blue'}}>
              nontouchable normal view.
            </Text>
          </View>
        </UIExplorerBlock>

        <UIExplorerBlock title="Accessible view with TextViews wihout label">
          <View accessible={true}>
            <Text style={{color: 'green',}}>
              This is
            </Text>
            <Text style={{color: 'blue'}}>
              nontouchable accessible view without label.
            </Text>
          </View>
        </UIExplorerBlock>

        <UIExplorerBlock title="Accessible view with TextViews with label">
          <View accessible={true}
            accessibilityLabel="I have label, so I read it instead of embedded text.">
            <Text style={{color: 'green',}}>
              This is
            </Text>
            <Text style={{color: 'blue'}}>
              nontouchable accessible view with label.
            </Text>
          </View>
        </UIExplorerBlock>

        <UIExplorerBlock title="Touchable with component type = button">
          <TouchableWithoutFeedback
            onPress={() => ToastAndroid.show('Toasts work by default', ToastAndroid.SHORT)}>
            <View style={styles.embedded} accessibilityComponentType="button">
              <Text>Click me</Text>
              <Text>Or not</Text>
            </View>
          </TouchableWithoutFeedback>
        </UIExplorerBlock>

        <UIExplorerBlock title="LiveRegion">
          <TouchableWithoutFeedback onPress={this._addOne}>
            <View style={styles.embedded} accessibilityComponentType="button">
              <Text>Click me</Text>
            </View>
          </TouchableWithoutFeedback>
          <Text accessibilityLiveRegion="polite">
            Clicked {this.state.count} times
          </Text>
        </UIExplorerBlock>

        <UIExplorerBlock title="Check if TouchExploration is enabled">
          <TouchableWithoutFeedback onPress={this._showAccessibilityToast}>
            <View style={styles.embedded}>
              <Text>
                Click to check TouchExploration
              </Text>
            </View>
          </TouchableWithoutFeedback>
        </UIExplorerBlock>

        <UIExplorerBlock title="Overlapping views and importantForAccessibility property">
          <View style={styles.container}>
            <View
              style={{
                position: 'absolute',
                left: 10,
                top: 10,
                right: 10,
                height: 100,
                backgroundColor: 'green'}}
              accessible={true}
              accessibilityLabel="First layout"
              importantForAccessibility={
                importantForAccessibilityValues[this.state.backgroundImportantForAcc]}>
              <View accessible={true}>
                <Text style={{fontSize: 25}}>
                  Hello
                </Text>
              </View>
            </View>
            <View
              style={{
                position: 'absolute',
                left: 10,
                top: 25,
                right: 10,
                height: 110,
                backgroundColor: 'yellow', opacity: 0.5}}
              accessible={true}
              accessibilityLabel="Second layout"
              importantForAccessibility={
                importantForAccessibilityValues[this.state.forgroundImportantForAcc]}>
              <View accessible={true}>
                <Text style={{fontSize: 20}}>
                  world
                </Text>
              </View>
            </View>
          </View>
          <TouchableWithoutFeedback onPress={this._changeBackgroundImportantForAcc}>
            <View style={styles.embedded}>
              <Text>
                Change importantForAccessibility for background layout.
              </Text>
            </View>
          </TouchableWithoutFeedback>
          <View accessible={true}>
            <Text>
              Background layout importantForAccessibility
            </Text>
            <Text>
              {importantForAccessibilityValues[this.state.backgroundImportantForAcc]}
            </Text>
          </View>
          <TouchableWithoutFeedback onPress={this._changeForgroundImportantForAcc}>
            <View style={styles.embedded}>
              <Text>
                Change importantForAccessibility for forground layout.
              </Text>
            </View>
          </TouchableWithoutFeedback>
          <View accessible={true}>
            <Text>
              Forground layout importantForAccessibility
            </Text>
            <Text>
              {importantForAccessibilityValues[this.state.forgroundImportantForAcc]}
            </Text>
          </View>
        </UIExplorerBlock>

      </UIExplorerPage>
    );
  },
});

var styles = StyleSheet.create({
   embedded: {
    backgroundColor: 'yellow',
    padding:10,
  },
  container: {
    flex: 1,
    backgroundColor: 'white',
    padding: 10,
    height:150,
  },
});

module.exports = AccessibilityAndroidExample;
<|endoftext|>


<commit_before>// Copyright (C) 2016 Goom Inc. All rights reserved.

import React, { PropTypes } from 'react';

export default React.createClass({
  propTypes: {
    boxClassName: PropTypes.string,
    items: PropTypes.array,
    onChangeText: PropTypes.func,
    onSelectItem: PropTypes.func,
    placeholder: PropTypes.string,
    text: PropTypes.string,
    resetDropdown: PropTypes.func,
  },
  getInitialState() {
    return { cursorPosition: -1 };
  },
  render() {
    const { items, boxClassName, placeholder,
      onSelectItem, resetDropdown, text, onChangeText } = this.props;

    let cursorPosition = this.state.cursorPosition;

    const renderItem = (item, index) => (
      <div key={item.text}
        className={`dropdown-item ${cursorPosition === index ? 'cursor' : ''}`}
        onClick={() => onSelectItem(item)}
      >

{item.text}

    );
    const renderDropdown = () => {
      if (items && items.length > 0) {
        return [
          (<div key={`${boxClassName}-dropdown-box`} className="dropdown-box open">
            {items.map(renderItem)}

),
          (<div key={`${boxClassName}-dropdown-box-overlay`} className="popup-overlay transparent" onClick={resetDropdown}>
), // eslint-disable-line
        ];
      }
      return (

);
    };
    const onKeyEvent = (e) => {
      const keyCode = e.keyCode;
      const changeCuror = (next) => {
        if (next !== cursorPosition) {
          this.setState({ cursorPosition: next });
          // $(`.${boxClassName} input`).val(items[next].text);
        }
      };
      if (keyCode === 38) {
        // arrow up
        changeCuror(Math.max(cursorPosition - 1, -1));
      } else if (keyCode === 40) {
        // arrow down
        changeCuror(Math.min(cursorPosition + 1, items.length - 1));
      } else if (keyCode === 13) {
        // enter
        if (cursorPosition === -1) {
          cursorPosition = 0;
        }
        onSelectItem(items[cursorPosition]);
      }
    };
    const onChange = (e) => {
      onChangeText(e.target.value);
      if (this.state.cursorPosition >= 0) {
        this.setState({ cursorPosition: -1 });
      }
    };
    const onFocus = (e) => {
      onChangeText(e.target.value);
    };
    const onBlur = () => {
      if (items && items.length === 1) {
        // 2016. 04. 19. [heekyu] select it if only one
        onSelectItem(items[0]);
      } else {
        resetDropdown();
      }
    };
    return (

        <input type="text"
          placeholder={placeholder}
          defaultValue={text}
          onFocus={onFocus}
          onChange={onChange}
          onKeyUp={onKeyEvent} // onKeyPress does not work for arrow up(38), down(40)
          onBlur={onBlur}
        />
        {renderDropdown()}

    );
  },
});
<commit_msg>do not auto select only one item<commit_after>// Copyright (C) 2016 Goom Inc. All rights reserved.

import React, { PropTypes } from 'react';

export default React.createClass({
  propTypes: {
    boxClassName: PropTypes.string,
    items: PropTypes.array,
    onChangeText: PropTypes.func,
    onSelectItem: PropTypes.func,
    placeholder: PropTypes.string,
    text: PropTypes.string,
    resetDropdown: PropTypes.func,
  },
  getInitialState() {
    return { cursorPosition: -1 };
  },
  render() {
    const { items, boxClassName, placeholder,
      onSelectItem, resetDropdown, text, onChangeText } = this.props;

    let cursorPosition = this.state.cursorPosition;

    const renderItem = (item, index) => (
      <div key={item.text}
        className={`dropdown-item ${cursorPosition === index ? 'cursor' : ''}`}
        onClick={() => onSelectItem(item)}
      >

{item.text}

    );
    const renderDropdown = () => {
      if (items && items.length > 0) {
        return [
          (<div key={`${boxClassName}-dropdown-box`} className="dropdown-box open">
            {items.map(renderItem)}

),
          (<div key={`${boxClassName}-dropdown-box-overlay`} className="popup-overlay transparent" onClick={resetDropdown}>
), // eslint-disable-line
        ];
      }
      return (

);
    };
    const onKeyEvent = (e) => {
      const keyCode = e.keyCode;
      const changeCuror = (next) => {
        if (next !== cursorPosition) {
          this.setState({ cursorPosition: next });
          // $(`.${boxClassName} input`).val(items[next].text);
        }
      };
      if (keyCode === 38) {
        // arrow up
        changeCuror(Math.max(cursorPosition - 1, -1));
      } else if (keyCode === 40) {
        // arrow down
        changeCuror(Math.min(cursorPosition + 1, items.length - 1));
      } else if (keyCode === 13) {
        // enter
        if (cursorPosition === -1) {
          cursorPosition = 0;
        }
        onSelectItem(items[cursorPosition]);
      }
    };
    const onChange = (e) => {
      onChangeText(e.target.value);
      if (this.state.cursorPosition >= 0) {
        this.setState({ cursorPosition: -1 });
      }
    };
    const onFocus = (e) => {
      onChangeText(e.target.value);
    };
    const onBlur = () => {
      resetDropdown();
    };
    return (

        <input type="text"
          placeholder={placeholder}
          defaultValue={text}
          onFocus={onFocus}
          onChange={onChange}
          onKeyUp={onKeyEvent} // onKeyPress does not work for arrow up(38), down(40)
          onBlur={onBlur}
        />
        {renderDropdown()}

    );
  },
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2017-present, Viro Media, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import {
  ViroARScene,
  ViroARPlane,
  ViroMaterials,
  ViroImage,
  ViroARPlaneSelector,
  ViroSurface,
  ViroConstants,
  ViroVideo,
  ViroText,
  ViroUtils
} from 'react-viro';

import TimerMixin from 'react-timer-mixin';

var createReactClass = require('create-react-class');

let polarToCartesian = ViroUtils.polarToCartesian;

var testARScene = createReactClass({
  mixins: [TimerMixin],
  getInitialState: function() {
    return {
      findPlanes : true,
      selectedState : "NOT Selected",
      numberOfPlanes : 2,
    }
  },
  render: function() {
    return (
      <ViroARScene anchorDetectionTypes={this.state.findPlanes ? "planes_horizontal" : "none"} >
        <ViroARPlaneSelector ref={"planeSelector"}
          maxPlanes={this.state.numberOfPlanes}
          onPlaneSelected={this._onPlaneSelected} >
          <ViroImage
            width={.2} height={.5}
            position={[0, .25, 0]}
            source={require("../res/ironman.png")}
            transformBehaviors="billboardY"
            onClick={this._onClick} />
        </ViroARPlaneSelector>

        <ViroText position={polarToCartesian([6, 0, 10])} text={"State: " + this.state.selectedState}
          style={styles.instructionText} transformBehaviors={["billboard"]}/>
        <ViroText position={polarToCartesian([6, 0, 0])} text={"MaxPlanes: " + this.state.numberOfPlanes}
          style={styles.instructionText} transformBehaviors={["billboard"]} onClick={this._numPlanesTextClick}/>
        <ViroText position={polarToCartesian([6, 0, -10])}
          text={this.state.findPlanes ? "Disable Plane Finding"  : "Enable Plane Finding"}
          onClick={()=>{this.setState({findPlanes : !this.state.findPlanes})}}
          style={styles.instructionText} transformBehaviors={["billboard"]}/>

        {/* Release Menu */}
        <ViroText position={polarToCartesian([6, -30, 0])} text={"Next test"}
          style={styles.instructionText} onClick={this._goToNextTest} transformBehaviors={["billboard"]}/>
        <ViroText position={polarToCartesian([6, -30, -15])} text={"Release Menu"}
          style={styles.instructionText} onClick={()=>{this.props.arSceneNavigator.replace("ARReleaseMenu", {scene: require("./ARReleaseMenu")})}}
          transformBehaviors={["billboard"]}/>
      </ViroARScene>
    );
  },
  _onPlaneSelected() {
    this.setState({
      selectedState : "Selected"
    })
  },
  _onClick() {
    this.refs["planeSelector"].reset();
    this.setState({
      selectedState : "NOT Selected"
    })
  },
  _numPlanesTextClick() {
    if (this.state.numberOfPlanes == 5) {
      this.setState({
        numberOfPlanes : 2
      })
    } else {
      this.setState({
        numberOfPlanes : this.state.numberOfPlanes + 1
      })
    }
  },
  _goToNextTest() {
    this.props.arSceneNavigator.replace("ARPlaneTest", {scene:require("./ARPlaneTest")})
  },
});

var styles = StyleSheet.create({
  instructionText: {
      fontFamily: 'Arial',
      fontSize: 25,
      width: 2,
      color: '#cccccc',
      flex: 1,
      textAlignVertical: 'center',
      textAlign: 'center',
  },
});

module.exports = testARScene;
<commit_msg>Fix plane detection test<commit_after>/**
 * Copyright (c) 2017-present, Viro Media, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import {
  ViroARScene,
  ViroARPlane,
  ViroMaterials,
  ViroImage,
  ViroARPlaneSelector,
  ViroSurface,
  ViroConstants,
  ViroVideo,
  ViroText,
  ViroUtils
} from 'react-viro';

import TimerMixin from 'react-timer-mixin';

var createReactClass = require('create-react-class');

let polarToCartesian = ViroUtils.polarToCartesian;

var testARScene = createReactClass({
  mixins: [TimerMixin],
  getInitialState: function() {
    return {
      findPlanes : true,
      selectedState : "NOT Selected",
      numberOfPlanes : 2,
    }
  },
  render: function() {
    return (
      <ViroARScene anchorDetectionTypes={this.state.findPlanes ? "planesHorizontal" : "none"} >
        <ViroARPlaneSelector ref={"planeSelector"}
          maxPlanes={this.state.numberOfPlanes}
          onPlaneSelected={this._onPlaneSelected} >
          <ViroImage
            width={.2} height={.5}
            position={[0, .25, 0]}
            source={require("../res/ironman.png")}
            transformBehaviors="billboardY"
            onClick={this._onClick} />
        </ViroARPlaneSelector>

        <ViroText position={polarToCartesian([6, 0, 10])} text={"State: " + this.state.selectedState}
          style={styles.instructionText} transformBehaviors={["billboard"]}/>
        <ViroText position={polarToCartesian([6, 0, 0])} text={"MaxPlanes: " + this.state.numberOfPlanes}
          style={styles.instructionText} transformBehaviors={["billboard"]} onClick={this._numPlanesTextClick}/>
        <ViroText position={polarToCartesian([6, 0, -10])}
          text={this.state.findPlanes ? "Disable Plane Finding"  : "Enable Plane Finding"}
          onClick={()=>{this.setState({findPlanes : !this.state.findPlanes})}}
          style={styles.instructionText} transformBehaviors={["billboard"]}/>

        {/* Release Menu */}
        <ViroText position={polarToCartesian([6, -30, 0])} text={"Next test"}
          style={styles.instructionText} onClick={this._goToNextTest} transformBehaviors={["billboard"]}/>
        <ViroText position={polarToCartesian([6, -30, -15])} text={"Release Menu"}
          style={styles.instructionText} onClick={()=>{this.props.arSceneNavigator.replace("ARReleaseMenu", {scene: require("./ARReleaseMenu")})}}
          transformBehaviors={["billboard"]}/>
      </ViroARScene>
    );
  },
  _onPlaneSelected() {
    this.setState({
      selectedState : "Selected"
    })
  },
  _onClick() {
    this.refs["planeSelector"].reset();
    this.setState({
      selectedState : "NOT Selected"
    })
  },
  _numPlanesTextClick() {
    if (this.state.numberOfPlanes == 5) {
      this.setState({
        numberOfPlanes : 2
      })
    } else {
      this.setState({
        numberOfPlanes : this.state.numberOfPlanes + 1
      })
    }
  },
  _goToNextTest() {
    this.props.arSceneNavigator.replace("ARPlaneTest", {scene:require("./ARPlaneTest")})
  },
});

var styles = StyleSheet.create({
  instructionText: {
      fontFamily: 'Arial',
      fontSize: 25,
      width: 2,
      color: '#cccccc',
      flex: 1,
      textAlignVertical: 'center',
      textAlign: 'center',
  },
});

module.exports = testARScene;
<|endoftext|>


<commit_before>
/**
 * 组织机构用户树的常用处理方法
 */
var org_user_tree = {

	/**
	 * 将组织的列表数据转为easyui-tree数据结构
	 * @param data
	 */
	orgDataConvertToEasyTreeData : function (rows){
		function exists(rows, pid){
			for(var i=0; i<rows.length; i++){
				if (rows[i].id == pid) return true;
			}
			return false;
		}

		var nodes = [];
		// get the top level nodes
		for(var i=0; i<rows.length; i++){
			var row = rows[i];
			if (!exists(rows, row.pid)){
				nodes.push({
					id:row.id,
					text:row.name,
					iconCls:row.iconCls?row.iconCls:""
				});
			}
		}

		var toDo = [];
		for(var i=0; i<nodes.length; i++){
			toDo.push(nodes[i]);
		}
		while(toDo.length){
			var node = toDo.shift();	// the parent node
			// get the children nodes
			for(var i=0; i<rows.length; i++){
				var row = rows[i];
				if (row.pid == node.id){
					var child = {id:row.id,text:row.name,
							iconCls:row.iconCls?row.iconCls:""};
					if (node.children){
						node.children.push(child);
					} else {
						node.children = [child];
					}
					toDo.push(child);
				}
			}
		}
		return nodes;
	}
}<commit_msg>修改组织、人员树，保留原始数据<commit_after>
/**
 * 组织机构用户树的常用处理方法
 */
var org_user_tree = {

	/**
	 * 将组织的列表数据转为easyui-tree数据结构
	 * @param data
	 */
	orgDataConvertToEasyTreeData : function (rows){
		function exists(rows, pid){
			for(var i=0; i<rows.length; i++){
				if (rows[i].id == pid) return true;
			}
			return false;
		}

		var nodes = [];
		// get the top level nodes
		for(var i=0; i<rows.length; i++){
			var row = rows[i];
			row.text = row.name;
			if (!exists(rows, row.pid)){
				nodes.push(row);
			}
		}

		var toDo = [];
		for(var i=0; i<nodes.length; i++){
			toDo.push(nodes[i]);
		}
		while(toDo.length){
			var node = toDo.shift();	// the parent node
			// get the children nodes
			for(var i=0; i<rows.length; i++){
				var row = rows[i];
				if (row.pid == node.id){
					if (node.children){
						node.children.push(row);
					} else {
						node.children = [row];
					}
					toDo.push(row);
				}
			}
		}
		return nodes;
	}
}<|endoftext|>


<commit_before>var signupDialogHelperInst = window.optly.mrkt.form.createAccount({formId: 'signup-form', dialogId: 'signup-dialog'});

w.optly.mrkt.activeModals = {};

w.optly.mrkt.activeModals.signup = new Oform({
  selector: '#signup-form',
  customValidation: {
    password1: function(elm) {
      return signupDialogHelperInst.password1Validate(elm);
    },
    password2: function(elm) {
      return signupDialogHelperInst.password2Validate(elm);
    }
  }
});

w.optly.mrkt.activeModals.signup.on('before', function() {
  //set the hidden input value
  signupDialogHelperInst.formElm.querySelector('[name="hidden"]').value = 'touched';
  signupDialogHelperInst.processingAdd();
  if(signupDialogHelperInst.characterMessageElm.classList.contains('oform-error-show')) {
    signupDialogHelperInst.characterMessageElm.classList.remove('oform-error-show');
  }
  return true;
});

w.optly.mrkt.activeModals.signup.on('validationerror', function(elm) {
  w.optly.mrkt.Oform.validationError(elm);
  signupDialogHelperInst.showOptionsError('Please Correct Form Errors');
  if(!signupDialogHelperInst.characterMessageElm.classList.contains('oform-error-show')) {
    signupDialogHelperInst.characterMessageElm.classList.add('oform-error-show');
  }
});

w.optly.mrkt.activeModals.signup.on('error', function() {
  signupDialogHelperInst.processingRemove({callee: 'error'});
  signupDialogHelperInst.showOptionsError('An unexpected error occurred. Please contact us if the problem persists.');
  window.analytics.track('create account xhr error', {
    category: 'account',
    label: w.location.pathname
  });
}.bind(signupDialogHelperInst));

w.optly.mrkt.activeModals.signup.on('load', function() {
  signupDialogHelperInst.load.bind(signupDialogHelperInst);
  window.location.href = '/pricing';
}.bind(signupDialogHelperInst));
<commit_msg>add done to signup modal<commit_after>var signupDialogHelperInst = window.optly.mrkt.form.createAccount({formId: 'signup-form', dialogId: 'signup-dialog'});

w.optly.mrkt.activeModals = {};

w.optly.mrkt.activeModals.signup = new Oform({
  selector: '#signup-form',
  customValidation: {
    password1: function(elm) {
      return signupDialogHelperInst.password1Validate(elm);
    },
    password2: function(elm) {
      return signupDialogHelperInst.password2Validate(elm);
    }
  }
});

w.optly.mrkt.activeModals.signup.on('before', function() {
  //set the hidden input value
  signupDialogHelperInst.formElm.querySelector('[name="hidden"]').value = 'touched';
  signupDialogHelperInst.processingAdd();
  if(signupDialogHelperInst.characterMessageElm.classList.contains('oform-error-show')) {
    signupDialogHelperInst.characterMessageElm.classList.remove('oform-error-show');
  }
  return true;
});

w.optly.mrkt.activeModals.signup.on('validationerror', function(elm) {
  w.optly.mrkt.Oform.validationError(elm);
  signupDialogHelperInst.showOptionsError('Please Correct Form Errors');
  if(!signupDialogHelperInst.characterMessageElm.classList.contains('oform-error-show')) {
    signupDialogHelperInst.characterMessageElm.classList.add('oform-error-show');
  }
});

w.optly.mrkt.activeModals.signup.on('error', function() {
  signupDialogHelperInst.processingRemove({callee: 'error'});
  signupDialogHelperInst.showOptionsError('An unexpected error occurred. Please contact us if the problem persists.');
  window.analytics.track('create account xhr error', {
    category: 'account',
    label: w.location.pathname
  });
}.bind(signupDialogHelperInst));

w.optly.mrkt.activeModals.signup.on('load', function() {
  signupDialogHelperInst.load.bind(signupDialogHelperInst);
  window.location.href = '/pricing';
});

w.optly.mrkt.activeModals.signup.on('done', function() {
  if (document.body.classList.contains('oform-error')) {
    signupDialogHelperInst.processingRemove({callee: 'done'});
  }
}.bind(signupDialogHelperInst));
<|endoftext|>


<commit_before>'use strict';

function Attachmentable(world) {

    this.object3D = new THREE.Object3D();
    this.world    = world;
    this.world.add_to_scene(this.object3D);

    this.immune_to_attachment_deltas = false;

    // All attachments will inherit Attachmentable.
    this.attachments = [];

    // The current object that has this instance as an attachment.
    this.attachment_parent = null;
    // The parent of this entire attachmentable chain.
    this.root_parent = null;
    // A name given to find this attachment later.
    this.relative_name = null;

    this.add_floating_wall_attachment = function(width, height, horizontal_offset, vertical_offset, depth_offset, scalable) {
        var temp_position = this.get_parent_position();

        var position = new THREE.Vector3(temp_position.x, temp_position.y, temp_position.z);
        var floating_wall;
        if (is_defined(scalable)) {
            // OLD : floating_wall = new FloatingWall(width, height, position, this.get_normal(), this.world, scalable);
            floating_wall = new FloatingWall(width, height, null, null, this.world, scalable);
        } else {
            floating_wall = new FloatingWall(width, height, null, null, this.world, false);
        }

        this.add_attachment(floating_wall);

        if (is_defined(horizontal_offset)) {
            floating_wall.set_attachment_horizontal_offset(horizontal_offset[0], horizontal_offset[1]);
        }
        if (is_defined(vertical_offset)) {
            floating_wall.set_attachment_vertical_offset(vertical_offset[0], vertical_offset[1]);
        }
        if (is_defined(depth_offset)) {
            floating_wall.set_attachment_depth_offset(depth_offset);
        }
        return floating_wall;
    };

    this.add_floating_2D_text = function(width, horizontal_offset, vertical_offset, depth_offset, text, type) {
        var floating_2D_text = new Floating2DText(width, text, type, this.world);

        this.add_attachment(floating_2D_text);

        if (is_defined(horizontal_offset)) {
            floating_2D_text.set_attachment_horizontal_offset(horizontal_offset[0], horizontal_offset[1]);
        }
        if (is_defined(vertical_offset)) {
            floating_2D_text.set_attachment_vertical_offset(vertical_offset[0], vertical_offset[1]);
        }
        if (is_defined(depth_offset)) {
            floating_2D_text.set_attachment_depth_offset(depth_offset);
        }
        return floating_2D_text;
    };

    this.refresh_position_and_look_at = function() {
        this._refresh_look_at();
        this.update_all_child_attachments();
    };

    // WARNING : This is recursive. Change the design later.
    this.update_all_child_attachments = function() {
        var parent_position = this.get_position();

        for (var a = 0; a < this.attachments.length; a++) {
            this.attachments[a].set_position(parent_position.x, parent_position.y, parent_position.z, false);
            this.attachments[a]._refresh_look_at();

            if (this.attachments.length > 0) {
                this.attachments[a].update_all_child_attachments();
            }
        }
    };

    /*    ___ ___       __               __
      /\   |   |   /\  /  ` |__| | |\ | / _`
     /~~\  |   |  /~~\ \__, |  | | | \| \__> */
    this.is_attached = function() {
        return !(this.attachment_parent === null);
    };

    this.detach_from_parent = function() {
        var remove_index = -1;

        // TEMPORARY FOR DEBUGGING
        var number_of_attachments = 0;

        for (var a = 0; a < this.attachment_parent.attachments.length; a++) {
            if (this.attachment_parent.attachments[a] === this) {
                remove_index = a;
                number_of_attachments += 1;
                //break;
            }
        }

        if (number_of_attachments > 1) {
            l('ERROR: NUMBER OF ATTACHMENTS IS GREATER THAN 1');
        }

        if (remove_index !== NOT_FOUND) {
            this.attachment_parent.attachments.slice(remove_index, 1);
            this.attachment_parent = null;
        }
    };

    this.attach_to = function(attachment_parent) {
        attachment_parent.add_attachment(this);
    };

    this.add_attachment = function(attachment) {
        this.attachments.push(attachment);
        if (this.is_root()) {
            attachment.root_parent = this;
        } else {
            attachment.root_parent = this.root_parent;
        }
        attachment.attachment_parent = this;
    };

    /*                    ___          __   __       ___  ___  __
     \  /  /\  |    |  | |__     |  | |__) |  \  /\   |  |__  /__`
      \/  /~~\ |___ \__/ |___    \__/ |    |__/ /~~\  |  |___ .__/ */
    this.update_height = function(percentage_change) {
        this.height *= percentage_change;
        this.update_dimensions();
    };

    this.update_width = function(percentage_change) {
        this.width *= percentage_change;
        this.update_dimensions();
    };

    this.update_dimensions = function() {
        if (this.scalable) {
            this.dimensions_changed();
        }
        for (var a = 0; a < this.attachments.length; a++) {
            if (this.attachments[a].scalable) {
                this.attachments[a].dimensions_changed();
                this.attachments[a].update_dimensions();
            }
        }
    };

    this.dimensions_changed = function() {
        this.delete_mesh();
        this.create_base_mesh();
    };

    /*__   ___ ___ ___  ___  __   __
     /__` |__   |   |  |__  |__) /__`
     .__/ |___  |   |  |___ |  \ .__/ */
    this.set_attachment_name = function(n) {
        this.relative_name = n;
    };

    this.look_at_origin = function(refresh) {
        // OLD : this.object3D.lookAt(-this.object3D.position.x, 0, -this.object3D.position.z);
        this.object3D.lookAt(0, this.object3D.position.y, 0);
        if (this.is_root()) {
            if (!is_defined(this.normal)) {
                // OLD : var normal = new THREE.Vector3(-this.object3D.position.x, 0, -this.object3D.position.z);
                var normal = new THREE.Vector3(-this.object3D.position.x, 0, -this.object3D.position.z);
                normal.normalize();
                this.normal = normal;
            }
        }
        if (refresh) {
            this._refresh_look_at();
        }
    };

    this.set_position = function(x, y, z, refresh) {
        if (this.is_root()) {
            this.object3D.position.set(x, y, z);
        } else {
            var position_offset = this.get_position_offset();
            this.object3D.position.set(x + position_offset[0], y + position_offset[1], z + position_offset[2]);
        }
        if (refresh) {
            this._refresh_look_at();
            this.update_all_child_attachments();
        }
    };

    // This function should only be called on a root element.
    this.set_normal = function(x, y, z, refresh) {
        this.normal = new THREE.Vector3(x, y, z);
        this.normal.normalize();
        this.left_right = get_left_right_unit_vector(-this.normal.x, -this.normal.z);
        if (refresh) {
            this._refresh_look_at();
            this.update_all_child_attachments();
        }
    };

    this.set_attachment_horizontal_offset = function(distance_offset, parent_width_percentage_offset) {
        // No need for is_defined checks as the values will be checked before being used.
        this.offset_horizontal_distance = distance_offset;
        this.offset_horizontal_parent_width_percentage = parent_width_percentage_offset;
    };

    this.apply_delta_to_horizontal_offset = function(distance_offset, parent_width_percentage_offset) {
        if (!this.immune_to_attachment_deltas) {
            if (is_defined(this.offset_horizontal_distance)) {
                this.offset_horizontal_distance += distance_offset;
            } else {
                this.offset_horizontal_distance = distance_offset;
            }
            if (is_defined(parent_width_percentage_offset)) {
                this.offset_horizontal_parent_width_percentage += parent_width_percentage_offset;
            } else {
                this.offset_horizontal_parent_width_percentage = parent_width_percentage_offset;
            }
        }
    };

    this.set_attachment_vertical_offset = function(distance_offset, parent_height_percentage_offset) {
        // No need for is_defined checks as the values will be checked before being used.
        this.offset_vertical_distance = distance_offset;
        this.offset_vertical_parent_height_percentage = parent_height_percentage_offset;
    };

    this.apply_delta_to_vertical_offset = function(distance_offset, parent_height_percentage_offset) {
        if (!this.immune_to_attachment_deltas) {
            if (is_defined(this.offset_vertical_distance)) {
                this.offset_vertical_distance += distance_offset;
            } else {
                this.offset_vertical_distance = distance_offset;
            }
            if (is_defined(this.offset_vertical_parent_height_percentage)) {
                this.offset_vertical_parent_height_percentage += parent_height_percentage_offset;
            } else {
                this.offset_vertical_parent_height_percentage = parent_height_percentage_offset;
            }
        }
    };

    this.set_attachment_depth_offset = function(depth_offset) {
        this.offset_normal_distance = depth_offset;
    };

    this.apply_delta_to_depth_offset = function(depth_offset) {
        if (!this.immune_to_attachment_deltas) {
            if (is_defined(this.offset_normal_distance)) {
                this.offset_normal_distance += depth_offset;
            } else {
                this.offset_normal_distance = depth_offset;
            }
        }
    };

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */
    this.get_attachment_vertical_offset = function() {
        return [this.offset_vertical_distance, this.offset_vertical_parent_height_percentage];
    };

    this.get_position_offset = function(n) {
        var normal;
        if (is_defined(n)) {
            normal = n;
        } else {
            normal = this.get_normal();
        }
        var dx = 0;
        var dy = 0;
        var dz = 0;
        var d;
        if (is_defined(this.offset_horizontal_distance)) {
            d = this.get_horizontal_shift(this.offset_horizontal_distance);
            dx += d.x;
            dy += d.y;
            dz += d.z;
        }
        if (is_defined(this.offset_horizontal_parent_width_percentage)) {
            d = this.get_horizontal_shift(this.attachment_parent.width * this.offset_horizontal_parent_width_percentage);
            dx += d.x;
            dy += d.y;
            dz += d.z;
        }
        // TODO : WARNING : For now this only supports y-normals of 0.
        if (is_defined(this.offset_vertical_distance)) {
            dy += this.offset_vertical_distance;
        }
        if (is_defined(this.offset_vertical_parent_height_percentage)) {
            dy += this.offset_vertical_parent_height_percentage * this.attachment_parent.height;
        }
        if (is_defined(this.offset_normal_distance)) {
            dx += normal.x * this.offset_normal_distance;
            dy += normal.y * this.offset_normal_distance;
            dz += normal.z * this.offset_normal_distance;
        }
        return [dx, dy, dz];
    };

    this.get_horizontal_distance_to_center = function(x, z) {
        return sqrt(squared(x - this.object3D.position.x) + squared(z - this.object3D.position.z));
    };

    this.get_horizontal_shift = function(distance) {
        var left_right = this.get_left_right();
        return new THREE.Vector3(left_right.x * distance, left_right.y * distance, left_right.z * distance);
    };

    this.get_parent_position = function() {
        return this.attachment_parent.object3D.position;
    };

    this.get_position = function() {
        return this.object3D.position;
    };

    // WARNING : This is recursive. Use different design later.
    this.get_normal = function() {
        if (is_defined(this.normal)) {
            return this.normal;
        } else {
            return this.attachment_parent.get_normal();
        }
    };

    // WARNING : This is recursive. Use different design later.
    this.get_left_right = function() {
        if (is_defined(this.left_right)) {
            return this.left_right;
        } else {
            return this.attachment_parent.get_left_right();
        }
    };

    this.is_root = function() {
        return !is_defined(this.attachment_parent);
    };

    this._get_all_attachments_recursively = function() {
        var attachments = [];
        for (var a = 0; a < this.attachments.length; a++) {
            attachments.push(this.attachments[a]);
            var attachments_of_this_attachment = this.attachments[a]._get_all_attachments_recursively();
            for (var aa = 0; aa < attachments_of_this_attachment.length; aa++) {
                attachments.push(attachments_of_this_attachment[aa]);
            }
        }
        return attachments;
    };

    /*__   ___  __   __        __   __   ___     __        ___                 __
     |__) |__  /__` /  \ |  | |__) /  ` |__     /  ` |    |__   /\  |\ | |  | |__)
     |  \ |___ .__/ \__/ \__/ |  \ \__, |___    \__, |___ |___ /~~\ | \| \__/ |    */
    // TODO : Refactor the design of this (resource cleanup needs to be cleaned up in general).
    this.remove_from_root_attachmentables_if_needed = function(object_to_check) {
        var index_to_remove = -1;
        for (var i = 0; i < this.world.root_attachables.length; i++) {
            if (this.world.root_attachables[i] === object_to_check) {
                index_to_remove = i;
                break;
            }
        }
        if (index_to_remove !== NOT_FOUND) {
            this.world.root_attachables.splice(index_to_remove, 1);
        }
    };

    this.fully_remove_self_and_all_sub_attachments = function() {
        for (var a = 0; a < this.attachments.length; a++) {
            this.attachments[a].fully_remove_self_and_all_sub_attachments();
        }

        this.remove_from_root_attachmentables_if_needed(this);
        this.world.remove_from_interactive_then_scene(this);
        this.full_remove();
    };

    /*      ___  ___  __                         ___          ___    ___  __
     | |\ |  |  |__  |__) |\ |  /\  |       |  |  |  | |    |  |  | |__  /__`
     | | \|  |  |___ |  \ | \| /~~\ |___    \__/  |  | |___ |  |  | |___ .__/ */
    this._refresh_look_at = function() {
        var normal = this.get_normal();
        var look_at_position = new THREE.Vector3(this.object3D.position.x + normal.x * 100, this.object3D.position.y + normal.y * 100, this.object3D.position.z + normal.z * 100);
        this.object3D.lookAt(look_at_position);
    };
}
<commit_msg>schedule features 14<commit_after>'use strict';

function Attachmentable(world) {

    this.object3D = new THREE.Object3D();
    this.world    = world;
    this.world.add_to_scene(this.object3D);

    this.immune_to_attachment_deltas = false;

    // All attachments will inherit Attachmentable.
    this.attachments = [];

    // The current object that has this instance as an attachment.
    this.attachment_parent = null;
    // The parent of this entire attachmentable chain.
    this.root_parent = null;
    // A name given to find this attachment later.
    this.relative_name = null;

    this.add_floating_wall_attachment = function(width, height, horizontal_offset, vertical_offset, depth_offset, scalable) {
        var temp_position = this.get_parent_position();

        var position = new THREE.Vector3(temp_position.x, temp_position.y, temp_position.z);
        var floating_wall;
        if (is_defined(scalable)) {
            // OLD : floating_wall = new FloatingWall(width, height, position, this.get_normal(), this.world, scalable);
            floating_wall = new FloatingWall(width, height, null, null, this.world, scalable);
        } else {
            floating_wall = new FloatingWall(width, height, null, null, this.world, false);
        }

        this.add_attachment(floating_wall);

        if (is_defined(horizontal_offset)) {
            floating_wall.set_attachment_horizontal_offset(horizontal_offset[0], horizontal_offset[1]);
        }
        if (is_defined(vertical_offset)) {
            floating_wall.set_attachment_vertical_offset(vertical_offset[0], vertical_offset[1]);
        }
        if (is_defined(depth_offset)) {
            floating_wall.set_attachment_depth_offset(depth_offset);
        }
        return floating_wall;
    };

    this.add_floating_2D_text = function(width, horizontal_offset, vertical_offset, depth_offset, text, type) {
        var floating_2D_text = new Floating2DText(width, text, type, this.world);

        this.add_attachment(floating_2D_text);

        if (is_defined(horizontal_offset)) {
            floating_2D_text.set_attachment_horizontal_offset(horizontal_offset[0], horizontal_offset[1]);
        }
        if (is_defined(vertical_offset)) {
            floating_2D_text.set_attachment_vertical_offset(vertical_offset[0], vertical_offset[1]);
        }
        if (is_defined(depth_offset)) {
            floating_2D_text.set_attachment_depth_offset(depth_offset);
        }
        return floating_2D_text;
    };

    this.refresh_position_and_look_at = function() {
        this._refresh_look_at();
        this.update_all_child_attachments();
    };

    // WARNING : This is recursive. Change the design later.
    this.update_all_child_attachments = function() {
        var parent_position = this.get_position();

        for (var a = 0; a < this.attachments.length; a++) {
            this.attachments[a].set_position(parent_position.x, parent_position.y, parent_position.z, false);
            this.attachments[a]._refresh_look_at();

            if (this.attachments.length > 0) {
                this.attachments[a].update_all_child_attachments();
            }
        }
    };

    /*    ___ ___       __               __
      /\   |   |   /\  /  ` |__| | |\ | / _`
     /~~\  |   |  /~~\ \__, |  | | | \| \__> */
    this.is_attached = function() {
        return !(this.attachment_parent === null);
    };

    this.detach_from_parent = function() {
        var remove_index = -1;

        // TEMPORARY FOR DEBUGGING
        var number_of_attachments = 0;

        for (var a = 0; a < this.attachment_parent.attachments.length; a++) {
            if (this.attachment_parent.attachments[a] === this) {
                remove_index = a;
                number_of_attachments += 1;
                //break;
            }
        }

        if (number_of_attachments > 1) {
            l('ERROR: NUMBER OF ATTACHMENTS IS GREATER THAN 1');
        } else if (number_of_attachments == 0) {
            l('ERROR: DID NOT FIND THE ATTACHMENT TO REMOVE!');
        }

        if (remove_index !== NOT_FOUND) {
            this.attachment_parent.attachments.slice(remove_index, 1);
            this.attachment_parent = null;
        }
    };

    this.attach_to = function(attachment_parent) {
        attachment_parent.add_attachment(this);
    };

    this.add_attachment = function(attachment) {
        this.attachments.push(attachment);
        if (this.is_root()) {
            attachment.root_parent = this;
        } else {
            attachment.root_parent = this.root_parent;
        }
        attachment.attachment_parent = this;
    };

    /*                    ___          __   __       ___  ___  __
     \  /  /\  |    |  | |__     |  | |__) |  \  /\   |  |__  /__`
      \/  /~~\ |___ \__/ |___    \__/ |    |__/ /~~\  |  |___ .__/ */
    this.update_height = function(percentage_change) {
        this.height *= percentage_change;
        this.update_dimensions();
    };

    this.update_width = function(percentage_change) {
        this.width *= percentage_change;
        this.update_dimensions();
    };

    this.update_dimensions = function() {
        if (this.scalable) {
            this.dimensions_changed();
        }
        for (var a = 0; a < this.attachments.length; a++) {
            if (this.attachments[a].scalable) {
                this.attachments[a].dimensions_changed();
                this.attachments[a].update_dimensions();
            }
        }
    };

    this.dimensions_changed = function() {
        this.delete_mesh();
        this.create_base_mesh();
    };

    /*__   ___ ___ ___  ___  __   __
     /__` |__   |   |  |__  |__) /__`
     .__/ |___  |   |  |___ |  \ .__/ */
    this.set_attachment_name = function(n) {
        this.relative_name = n;
    };

    this.look_at_origin = function(refresh) {
        // OLD : this.object3D.lookAt(-this.object3D.position.x, 0, -this.object3D.position.z);
        this.object3D.lookAt(0, this.object3D.position.y, 0);
        if (this.is_root()) {
            if (!is_defined(this.normal)) {
                // OLD : var normal = new THREE.Vector3(-this.object3D.position.x, 0, -this.object3D.position.z);
                var normal = new THREE.Vector3(-this.object3D.position.x, 0, -this.object3D.position.z);
                normal.normalize();
                this.normal = normal;
            }
        }
        if (refresh) {
            this._refresh_look_at();
        }
    };

    this.set_position = function(x, y, z, refresh) {
        if (this.is_root()) {
            this.object3D.position.set(x, y, z);
        } else {
            var position_offset = this.get_position_offset();
            this.object3D.position.set(x + position_offset[0], y + position_offset[1], z + position_offset[2]);
        }
        if (refresh) {
            this._refresh_look_at();
            this.update_all_child_attachments();
        }
    };

    // This function should only be called on a root element.
    this.set_normal = function(x, y, z, refresh) {
        this.normal = new THREE.Vector3(x, y, z);
        this.normal.normalize();
        this.left_right = get_left_right_unit_vector(-this.normal.x, -this.normal.z);
        if (refresh) {
            this._refresh_look_at();
            this.update_all_child_attachments();
        }
    };

    this.set_attachment_horizontal_offset = function(distance_offset, parent_width_percentage_offset) {
        // No need for is_defined checks as the values will be checked before being used.
        this.offset_horizontal_distance = distance_offset;
        this.offset_horizontal_parent_width_percentage = parent_width_percentage_offset;
    };

    this.apply_delta_to_horizontal_offset = function(distance_offset, parent_width_percentage_offset) {
        if (!this.immune_to_attachment_deltas) {
            if (is_defined(this.offset_horizontal_distance)) {
                this.offset_horizontal_distance += distance_offset;
            } else {
                this.offset_horizontal_distance = distance_offset;
            }
            if (is_defined(parent_width_percentage_offset)) {
                this.offset_horizontal_parent_width_percentage += parent_width_percentage_offset;
            } else {
                this.offset_horizontal_parent_width_percentage = parent_width_percentage_offset;
            }
        }
    };

    this.set_attachment_vertical_offset = function(distance_offset, parent_height_percentage_offset) {
        // No need for is_defined checks as the values will be checked before being used.
        this.offset_vertical_distance = distance_offset;
        this.offset_vertical_parent_height_percentage = parent_height_percentage_offset;
    };

    this.apply_delta_to_vertical_offset = function(distance_offset, parent_height_percentage_offset) {
        if (!this.immune_to_attachment_deltas) {
            if (is_defined(this.offset_vertical_distance)) {
                this.offset_vertical_distance += distance_offset;
            } else {
                this.offset_vertical_distance = distance_offset;
            }
            if (is_defined(this.offset_vertical_parent_height_percentage)) {
                this.offset_vertical_parent_height_percentage += parent_height_percentage_offset;
            } else {
                this.offset_vertical_parent_height_percentage = parent_height_percentage_offset;
            }
        }
    };

    this.set_attachment_depth_offset = function(depth_offset) {
        this.offset_normal_distance = depth_offset;
    };

    this.apply_delta_to_depth_offset = function(depth_offset) {
        if (!this.immune_to_attachment_deltas) {
            if (is_defined(this.offset_normal_distance)) {
                this.offset_normal_distance += depth_offset;
            } else {
                this.offset_normal_distance = depth_offset;
            }
        }
    };

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */
    this.get_attachment_vertical_offset = function() {
        return [this.offset_vertical_distance, this.offset_vertical_parent_height_percentage];
    };

    this.get_position_offset = function(n) {
        var normal;
        if (is_defined(n)) {
            normal = n;
        } else {
            normal = this.get_normal();
        }
        var dx = 0;
        var dy = 0;
        var dz = 0;
        var d;
        if (is_defined(this.offset_horizontal_distance)) {
            d = this.get_horizontal_shift(this.offset_horizontal_distance);
            dx += d.x;
            dy += d.y;
            dz += d.z;
        }
        if (is_defined(this.offset_horizontal_parent_width_percentage)) {
            d = this.get_horizontal_shift(this.attachment_parent.width * this.offset_horizontal_parent_width_percentage);
            dx += d.x;
            dy += d.y;
            dz += d.z;
        }
        // TODO : WARNING : For now this only supports y-normals of 0.
        if (is_defined(this.offset_vertical_distance)) {
            dy += this.offset_vertical_distance;
        }
        if (is_defined(this.offset_vertical_parent_height_percentage)) {
            dy += this.offset_vertical_parent_height_percentage * this.attachment_parent.height;
        }
        if (is_defined(this.offset_normal_distance)) {
            dx += normal.x * this.offset_normal_distance;
            dy += normal.y * this.offset_normal_distance;
            dz += normal.z * this.offset_normal_distance;
        }
        return [dx, dy, dz];
    };

    this.get_horizontal_distance_to_center = function(x, z) {
        return sqrt(squared(x - this.object3D.position.x) + squared(z - this.object3D.position.z));
    };

    this.get_horizontal_shift = function(distance) {
        var left_right = this.get_left_right();
        return new THREE.Vector3(left_right.x * distance, left_right.y * distance, left_right.z * distance);
    };

    this.get_parent_position = function() {
        return this.attachment_parent.object3D.position;
    };

    this.get_position = function() {
        return this.object3D.position;
    };

    // WARNING : This is recursive. Use different design later.
    this.get_normal = function() {
        if (is_defined(this.normal)) {
            return this.normal;
        } else {
            return this.attachment_parent.get_normal();
        }
    };

    // WARNING : This is recursive. Use different design later.
    this.get_left_right = function() {
        if (is_defined(this.left_right)) {
            return this.left_right;
        } else {
            return this.attachment_parent.get_left_right();
        }
    };

    this.is_root = function() {
        return !is_defined(this.attachment_parent);
    };

    this._get_all_attachments_recursively = function() {
        var attachments = [];
        for (var a = 0; a < this.attachments.length; a++) {
            attachments.push(this.attachments[a]);
            var attachments_of_this_attachment = this.attachments[a]._get_all_attachments_recursively();
            for (var aa = 0; aa < attachments_of_this_attachment.length; aa++) {
                attachments.push(attachments_of_this_attachment[aa]);
            }
        }
        return attachments;
    };

    /*__   ___  __   __        __   __   ___     __        ___                 __
     |__) |__  /__` /  \ |  | |__) /  ` |__     /  ` |    |__   /\  |\ | |  | |__)
     |  \ |___ .__/ \__/ \__/ |  \ \__, |___    \__, |___ |___ /~~\ | \| \__/ |    */
    // TODO : Refactor the design of this (resource cleanup needs to be cleaned up in general).
    this.remove_from_root_attachmentables_if_needed = function(object_to_check) {
        var index_to_remove = -1;
        for (var i = 0; i < this.world.root_attachables.length; i++) {
            if (this.world.root_attachables[i] === object_to_check) {
                index_to_remove = i;
                break;
            }
        }
        if (index_to_remove !== NOT_FOUND) {
            this.world.root_attachables.splice(index_to_remove, 1);
        }
    };

    this.fully_remove_self_and_all_sub_attachments = function() {
        for (var a = 0; a < this.attachments.length; a++) {
            this.attachments[a].fully_remove_self_and_all_sub_attachments();
        }

        this.remove_from_root_attachmentables_if_needed(this);
        this.world.remove_from_interactive_then_scene(this);
        this.full_remove();
    };

    /*      ___  ___  __                         ___          ___    ___  __
     | |\ |  |  |__  |__) |\ |  /\  |       |  |  |  | |    |  |  | |__  /__`
     | | \|  |  |___ |  \ | \| /~~\ |___    \__/  |  | |___ |  |  | |___ .__/ */
    this._refresh_look_at = function() {
        var normal = this.get_normal();
        var look_at_position = new THREE.Vector3(this.object3D.position.x + normal.x * 100, this.object3D.position.y + normal.y * 100, this.object3D.position.z + normal.z * 100);
        this.object3D.lookAt(look_at_position);
    };
}
<|endoftext|>


<commit_before>'use strict';

var app = app || {};

(function(module) {
  const repoController = {};

  repoController.index = () => {
    $('.content').children().hide();
    $('#content-portfolio').show();
    console.log('hi repoController.index');
    app.repos.requestRepos(app.repoView.index);
  };

  module.repoController = repoController;
})(app);
<commit_msg>initial commit<commit_after>'use strict';

var app = app || {};

(function(module) {
  const repoController = {};

  repoController.index = () => {
    $('.content').children().hide();
    $('#content-portfolio').show();
    app.repos.requestRepos(app.repoView.index);
  };

  module.repoController = repoController;
})(app);
<|endoftext|>


<commit_before>var _ = require('lazy.js');
var blessed = require('blessed');
var fs = require('fs');
var path = require('path');

var Editor = require('./editor');
var Coordinate = require('./coordinate');
var markup = require('./markup');
var util = require('./util');
var textUtil = require('./textUtil');

function Slap (opts) {
  var self = this;

  if (!(self instanceof blessed.Node)) { return new Slap(opts); }

  blessed.Screen.call(self, opts);

  self.header = new blessed.Box(_({
    tags: true,
    top: 0,
    left: 0,
    right: 0,
    height: 1
  }).merge(opts.header || {}).merge({parent: self}).toObject());

  self.editor = new Editor(_({
    parent: self,
    top: 1,
    left: 0,
    right: 0,
    bottom: 0
  }).merge(opts.editor || {}).toObject());
  self.editor.focus();

  self._initHandlers().render();
}
Slap.prototype.__proto__ = blessed.Screen.prototype;

Slap.normalizePath = function (givenPath) {
  if (!givenPath) { givenPath = ''; }
  if (givenPath[0] === '~') { givenPath = path.join(process.env.HOME, givenPath.slice(1)); }
  return path.normalize(givenPath);
};
Slap.prototype.path = util.getterSetter('path', null, Slap.normalizePath);
Slap.prototype.open = function (givenPath) {
  var self = this;

  givenPath = Slap.normalizePath(givenPath);
  fs.readFile(givenPath, function (err, data) {
    if (err) { throw err; }
    self.path(givenPath);

    self.editor.text(data, givenPath.split('.').pop());
  });

  return self;
};
Slap.prototype.save = function (givenPath) {
  var self = this;
  givenPath = givenPath ? Slap.normalizePath(givenPath) : self.path();
  if (!givenPath) { return; }

  var text = self.editor.text();
  fs.writeFile(givenPath, text, {flags: 'w'}, function (err) {
    if (!err) {
      self
        .path(givenPath)
        .message("saved to " + givenPath, 'success');
      self.editor.changeStack.save();
      self.emit('save', givenPath, text);
    } else {
      switch (err.code) {
        case 'EACCES': case 'EISDIR':
          self.message(err.message, 'error');
          break;
        default: throw err;
      }
    }
  });
};
Slap.prototype.saveAs = function () {
  var self = this;
  self.prompt("save as", function (results) {
    if (results) {
      self.save(results[0]);
    }
  });
};

Slap.prototype.prompt = function (prompts, cb) {
  var self = this;

  prompts = typeof prompts !== 'string' ? prompts : [prompts];

  self.closePrompt();
  self.editor.bottom += prompts.length;
  self.form = new blessed.Form({
    parent: self,
    height: prompts.length,
    left: 0,
    right: 0,
    bottom: 0
  });

  var labelWidth = _(prompts).pluck('length').max() + 3;
  var label = new blessed.Box({
    parent: self.form,
    tags: true,
    content: prompts.map(function (prompt) {
      return markup.markupLine(
        (' ' + prompt + ':' + _.repeat(' ', labelWidth).join('')).slice(0, labelWidth),
      self.options.style.prompt || self.options.style.main);
    }).join('\n'),
    top: 0,
    left: 0,
    width: labelWidth,
    bottom: 0
  });

  function done (submit) {
    self.closePrompt(true);
    cb(submit ? _(inputs).pluck('value').toArray() : null);

    // FIXME: nasty hack to stop Enter key event propagating to the wrong element
    self.lockKeys = true;
    process.nextTick(function () { self.lockKeys = false; });
  }

  var inputs = prompts.map(function (prompt, i) {
    var input = new blessed.Textbox(_(self.options.editor || {}).merge({
      parent: self.form,
      inputOnFocus: true,
      top: i,
      height: 1,
      left: labelWidth,
      right: 0
    }).merge(self.options.input || {}).toObject());
    if (!i) { input.focus(); }
    input.on('submit', done.bind(null, true));
    input.on('cancel', done.bind(null, false));
    return input;
  });

  self.render();
  return self;
};

Slap.prototype.closePrompt = function (focus) {
  var self = this;

  if (self.form) {
    self.remove(self.form);
    self.form = null;
    if (focus) { self.editor.focus(); }
    self.editor.bottom = 0;
    self.render();
  }

  return self;
};

Slap.prototype.exit = function () {
  process.exit(0);

  return this; // Just in case
};

Slap.prototype.message = util.getterSetter('message', null, function (message, styleName) {
  var self = this;

  clearTimeout(self.data.messageTimer);
  self.data.messageTimer = setTimeout(function () {
    self.message(null);
  }, self.options.messageDuration);

  return message !== null ? markup.markupLine(message, self.options.style[styleName]) : null;
});

Slap._regExpRegExp = /^\/(.+)\/$/;
Slap.prototype._initHandlers = function () {
  var self = this;

  var style = self.options.style;
  self.on('element keypress', function (el, ch, key) {
    self.message(null);
    switch (util.getBinding(self.options.bindings, key)) {
      case 'quit':
        if (self.editor.changeStack.dirty()) {
          self.exit(); // FIXME: warn user focused element needs finishing
        } else {
          self.exit();
        }
        break;
      case 'find':
        self.prompt("find (/.*/ for regex)", function (results) {
          if (results) {
            pattern = results[0];
            var regExpMatch = pattern.match(Slap._regExpRegExp);
            pattern = regExpMatch
              ? new RegExp(regExpMatch[1])
              : new RegExp(textUtil.escapeRegExp(pattern));

            var startPos = self.editor.cursor();
            startPos.x += 1;
            var pos = textUtil.find(self.editor.lines(), pattern, startPos);

            if (pos) {
              self.editor.select(null, pos);
            } else {
              pos = textUtil.find(self.editor.lines(), pattern);
              if (pos) {
                self.message(Coordinate.linear.cmp(pos, self.editor.cursor()) !== 0
                  ? "search wrapped"
                  : "this is the only occurrence", 'info');
                self.editor.select(null, pos);
              } else {
                self.message("no matches", 'warning');
              }
            }
          }
        });
        break;
      case 'save':
        if (self.path()) { self.save(); }
        else { self.saveAs(); }
        break;
      case 'saveAs':
        self.saveAs();
        break;
    }
  });

  ['resize', 'message', 'save'].forEach(function (evt) {
    self.on(evt, function () { self.render(); });
  });

  ['change', 'cursor', 'insertMode'].forEach(function (evt) {
    self.editor.on(evt, function () { self.render(); });
  });

  return self;
};
Slap.prototype.render = function () {
  var self = this;

  var style = self.options.style;
  var cursor = self.editor.cursor();

  var left = ' \u270b ';
  var originalPath = self.path();
  var markupPath = markup.escapeCurlies(originalPath || 'new file');
  if (self.editor.changeStack.dirty() || !originalPath) {
    markupPath = markup.markupLine(markupPath+'*', style.changed);
  }
  left += markupPath;

  var right = [(cursor.y + 1)+','+(cursor.x + 1) + ' ('+self.editor.lines().length+')'];
  if (!self.editor.insertMode()) { right.unshift(markup.markupLine('ovr', '{red-bg}{white-fg}')); }
  var message = self.message();
  if (message) {
    right.unshift(markup.markupLine(message, self.data.blink ? style.blink : ''));
    if (self.options.blinkRate && !self.data.messageBlinkTimer) {
      (function blink () {
        self.data.messageBlinkTimer = setTimeout(function () {
          self.data.blink = !self.data.blink;
          self.render();
          blink();
        }, self.options.blinkRate);
      }());
    }
  } else {
    clearTimeout(self.data.messageBlinkTimer);
    self.data.messageBlinkTimer = false;
    self.data.blink = false;
  }
  right = right.join('  ') + ' ';

  var remainingWidth = self.header.width - self.header.iwidth - markup.removeMarkup(left + right).length;
  self.header.setContent(markup.markupLine(
    left + _.repeat(' ', remainingWidth).join('') + right
  , style.header || style.main));

  return blessed.Screen.prototype.render.apply(self, arguments);
};

module.exports = Slap;
<commit_msg>Let's give that message some whitespace... messages love whitespace<commit_after>var _ = require('lazy.js');
var blessed = require('blessed');
var fs = require('fs');
var path = require('path');

var Editor = require('./editor');
var Coordinate = require('./coordinate');
var markup = require('./markup');
var util = require('./util');
var textUtil = require('./textUtil');

function Slap (opts) {
  var self = this;

  if (!(self instanceof blessed.Node)) { return new Slap(opts); }

  blessed.Screen.call(self, opts);

  self.header = new blessed.Box(_({
    tags: true,
    top: 0,
    left: 0,
    right: 0,
    height: 1
  }).merge(opts.header || {}).merge({parent: self}).toObject());

  self.editor = new Editor(_({
    parent: self,
    top: 1,
    left: 0,
    right: 0,
    bottom: 0
  }).merge(opts.editor || {}).toObject());
  self.editor.focus();

  self._initHandlers().render();
}
Slap.prototype.__proto__ = blessed.Screen.prototype;

Slap.normalizePath = function (givenPath) {
  if (!givenPath) { givenPath = ''; }
  if (givenPath[0] === '~') { givenPath = path.join(process.env.HOME, givenPath.slice(1)); }
  return path.normalize(givenPath);
};
Slap.prototype.path = util.getterSetter('path', null, Slap.normalizePath);
Slap.prototype.open = function (givenPath) {
  var self = this;

  givenPath = Slap.normalizePath(givenPath);
  fs.readFile(givenPath, function (err, data) {
    if (err) { throw err; }
    self.path(givenPath);

    self.editor.text(data, givenPath.split('.').pop());
  });

  return self;
};
Slap.prototype.save = function (givenPath) {
  var self = this;
  givenPath = givenPath ? Slap.normalizePath(givenPath) : self.path();
  if (!givenPath) { return; }

  var text = self.editor.text();
  fs.writeFile(givenPath, text, {flags: 'w'}, function (err) {
    if (!err) {
      self
        .path(givenPath)
        .message("saved to " + givenPath, 'success');
      self.editor.changeStack.save();
      self.emit('save', givenPath, text);
    } else {
      switch (err.code) {
        case 'EACCES': case 'EISDIR':
          self.message(err.message, 'error');
          break;
        default: throw err;
      }
    }
  });
};
Slap.prototype.saveAs = function () {
  var self = this;
  self.prompt("save as", function (results) {
    if (results) {
      self.save(results[0]);
    }
  });
};

Slap.prototype.prompt = function (prompts, cb) {
  var self = this;

  prompts = typeof prompts !== 'string' ? prompts : [prompts];

  self.closePrompt();
  self.editor.bottom += prompts.length;
  self.form = new blessed.Form({
    parent: self,
    height: prompts.length,
    left: 0,
    right: 0,
    bottom: 0
  });

  var labelWidth = _(prompts).pluck('length').max() + 3;
  var label = new blessed.Box({
    parent: self.form,
    tags: true,
    content: prompts.map(function (prompt) {
      return markup.markupLine(
        (' ' + prompt + ':' + _.repeat(' ', labelWidth).join('')).slice(0, labelWidth),
      self.options.style.prompt || self.options.style.main);
    }).join('\n'),
    top: 0,
    left: 0,
    width: labelWidth,
    bottom: 0
  });

  function done (submit) {
    self.closePrompt(true);
    cb(submit ? _(inputs).pluck('value').toArray() : null);

    // FIXME: nasty hack to stop Enter key event propagating to the wrong element
    self.lockKeys = true;
    process.nextTick(function () { self.lockKeys = false; });
  }

  var inputs = prompts.map(function (prompt, i) {
    var input = new blessed.Textbox(_(self.options.editor || {}).merge({
      parent: self.form,
      inputOnFocus: true,
      top: i,
      height: 1,
      left: labelWidth,
      right: 0
    }).merge(self.options.input || {}).toObject());
    if (!i) { input.focus(); }
    input.on('submit', done.bind(null, true));
    input.on('cancel', done.bind(null, false));
    return input;
  });

  self.render();
  return self;
};

Slap.prototype.closePrompt = function (focus) {
  var self = this;

  if (self.form) {
    self.remove(self.form);
    self.form = null;
    if (focus) { self.editor.focus(); }
    self.editor.bottom = 0;
    self.render();
  }

  return self;
};

Slap.prototype.exit = function () {
  process.exit(0);

  return this; // Just in case
};

Slap.prototype.message = util.getterSetter('message', null, function (message, styleName) {
  var self = this;

  clearTimeout(self.data.messageTimer);
  self.data.messageTimer = setTimeout(function () {
    self.message(null);
  }, self.options.messageDuration);

  return message !== null ? markup.markupLine(' '+message+' ', self.options.style[styleName]) : null;
});

Slap._regExpRegExp = /^\/(.+)\/$/;
Slap.prototype._initHandlers = function () {
  var self = this;

  var style = self.options.style;
  self.on('element keypress', function (el, ch, key) {
    self.message(null);
    switch (util.getBinding(self.options.bindings, key)) {
      case 'quit':
        if (self.editor.changeStack.dirty()) {
          self.exit(); // FIXME: warn user focused element needs finishing
        } else {
          self.exit();
        }
        break;
      case 'find':
        self.prompt("find (/.*/ for regex)", function (results) {
          if (results) {
            pattern = results[0];
            var regExpMatch = pattern.match(Slap._regExpRegExp);
            pattern = regExpMatch
              ? new RegExp(regExpMatch[1])
              : new RegExp(textUtil.escapeRegExp(pattern));

            var startPos = self.editor.cursor();
            startPos.x += 1;
            var pos = textUtil.find(self.editor.lines(), pattern, startPos);

            if (pos) {
              self.editor.select(null, pos);
            } else {
              pos = textUtil.find(self.editor.lines(), pattern);
              if (pos) {
                self.message(Coordinate.linear.cmp(pos, self.editor.cursor()) !== 0
                  ? "search wrapped"
                  : "this is the only occurrence", 'info');
                self.editor.select(null, pos);
              } else {
                self.message("no matches", 'warning');
              }
            }
          }
        });
        break;
      case 'save':
        if (self.path()) { self.save(); }
        else { self.saveAs(); }
        break;
      case 'saveAs':
        self.saveAs();
        break;
    }
  });

  ['resize', 'message', 'save'].forEach(function (evt) {
    self.on(evt, function () { self.render(); });
  });

  ['change', 'cursor', 'insertMode'].forEach(function (evt) {
    self.editor.on(evt, function () { self.render(); });
  });

  return self;
};
Slap.prototype.render = function () {
  var self = this;

  var style = self.options.style;
  var cursor = self.editor.cursor();

  var left = ' \u270b ';
  var originalPath = self.path();
  var markupPath = markup.escapeCurlies(originalPath || 'new file');
  if (self.editor.changeStack.dirty() || !originalPath) {
    markupPath = markup.markupLine(markupPath+'*', style.changed);
  }
  left += markupPath;

  var right = [(cursor.y + 1)+','+(cursor.x + 1) + ' ('+self.editor.lines().length+')'];
  if (!self.editor.insertMode()) { right.unshift(markup.markupLine('ovr', '{red-bg}{white-fg}')); }
  var message = self.message();
  if (message) {
    right.unshift(markup.markupLine(message, self.data.blink ? style.blink : ''));
    if (self.options.blinkRate && !self.data.messageBlinkTimer) {
      (function blink () {
        self.data.messageBlinkTimer = setTimeout(function () {
          self.data.blink = !self.data.blink;
          self.render();
          blink();
        }, self.options.blinkRate);
      }());
    }
  } else {
    clearTimeout(self.data.messageBlinkTimer);
    self.data.messageBlinkTimer = false;
    self.data.blink = false;
  }
  right = right.join('  ') + ' ';

  var remainingWidth = self.header.width - self.header.iwidth - markup.removeMarkup(left + right).length;
  self.header.setContent(markup.markupLine(
    left + _.repeat(' ', remainingWidth).join('') + right
  , style.header || style.main));

  return blessed.Screen.prototype.render.apply(self, arguments);
};

module.exports = Slap;
<|endoftext|>


<commit_before>"use strict";

var url = require('url'),
    builder = require('xmlbuilder'),
    request = require('request'),
    splitter = require('./multipartSplitter'),
    es = require('event-stream');

var RE_BOUNDARY = /^multipart\/.+?(?:;\s+boundary=(?:(?:"(.+)")|(?:([^\s]+))))$/i;

function getBoundary(response) {
  var matcher = RE_BOUNDARY.exec(response.headers['content-type']);
  return matcher ? matcher[1] : null;
}

module.exports = function(endpoint) {

  var parsedUrl = url.parse(endpoint);

  function createEnvelope(body) {

    var envelope = builder.create('soap:Envelope', {headless: true});
    envelope.att('xmlns:soap', "http://schemas.xmlsoap.org/soap/envelope/");
    envelope.ele("soap:Header");
    var bodyTag = envelope.ele("soap:Body");

    bodyTag.raw(body);

    return envelope.end();

  }

  function sendRequest(method, envelope, cb) {

    var options = {
      url: endpoint,
      method: 'POST',
      body: envelope,
      headers: {
        "Content-Type": "text/xml",
        "SOAPAction": '"http://' + parsedUrl.hostname + parsedUrl.pathname + '/' + method + '"'
      }
    };

    var through = es.through();

    request(options)
      .on('response', function(response) {

        if (response.statusCode !== 200 || /^text\/xml/.test(response.headers['content-type'])) {
          var errorWriter = es.wait(function(err, text) {
            through.emit('error', "Error from jasper server: " + text);
          });
          response.pipe(errorWriter);
          return;
        }

        var boundary = getBoundary(response);

        if (boundary) {
          splitter(boundary, response).pipe(through);
        } else {
          response.pipe(through);
        }

      })
      .on('error', function(err) {
        through.emit('error', err);
      });

    cb(null, through);

  }

  function call(method, body, cb) {
    var envelope = createEnvelope(body);
    sendRequest(method, envelope, cb);
  }

  return  {
    call: call
  };

};<commit_msg>Refactor callback for soap interface<commit_after>"use strict";

var url = require('url'),
    builder = require('xmlbuilder'),
    request = require('request'),
    splitter = require('./multipartSplitter'),
    es = require('event-stream');

var RE_BOUNDARY = /^multipart\/.+?(?:;\s+boundary=(?:(?:"(.+)")|(?:([^\s]+))))$/i;

function getBoundary(response) {
  var matcher = RE_BOUNDARY.exec(response.headers['content-type']);
  return matcher ? matcher[1] : null;
}

module.exports = function(endpoint) {

  var parsedUrl = url.parse(endpoint);

  function createEnvelope(body) {

    var envelope = builder.create('soap:Envelope', {headless: true});
    envelope.att('xmlns:soap', "http://schemas.xmlsoap.org/soap/envelope/");
    envelope.ele("soap:Header");
    var bodyTag = envelope.ele("soap:Body");

    bodyTag.raw(body);

    return envelope.end();

  }

  function sendRequest(method, envelope, cb) {

    var options = {
      url: endpoint,
      method: 'POST',
      body: envelope,
      headers: {
        "Content-Type": "text/xml",
        "SOAPAction": '"http://' + parsedUrl.hostname + parsedUrl.pathname + '/' + method + '"'
      }
    };

    request(options)
      .on('response', function(response) {

        if (response.statusCode !== 200 || /^text\/xml/.test(response.headers['content-type'])) {
          var errorWriter = es.wait(function(err, text) {
            cb("Unexpected result from jasper server: status(" + response.statusCode + ") content-type(" + response.headers["content-type"] + ") Body: " + text);
          });
          response.pipe(errorWriter);
          return;
        }

        var through = es.through();

        var boundary = getBoundary(response);

        if (boundary) {
          splitter(boundary, response).pipe(through);
        } else {
          response.pipe(through);
        }

        cb(null, through);

      })
      .on('error', function(err) {
        cb(err);
      });

  }

  function call(method, body, cb) {
    var envelope = createEnvelope(body);
    sendRequest(method, envelope, cb);
  }

  return  {
    call: call
  };

};<|endoftext|>


<commit_before>module.exports = sortByProcedure;

/*
	sort the parts of the passed selector,
	as there is potential for optimization
	(some types of selectors are faster than others)
*/

var procedure = {
    __proto__: null,
    universal: 5, //should be last so that it can be ignored
    tag: 3, //very quick test
    attribute: 1,
    pseudo: 0, //can be pretty expensive (especially :has)

    //everything else shouldn't be moved
    descendant: -1,
    child: -1,
    parent: -1,
    sibling: -1,
    adjacent: -1
};

function sortByProcedure(arr) {
    for (var i = 1; i < arr.length; i++) {
        var procNew = procedure[arr[i].type];

        if (procNew < 0) continue;

        for (var j = i - 1; j >= 0 && procNew < procedure[arr[j].type]; j--) {
            var tmp = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = tmp;
        }
    }
    return arr;
}
<commit_msg>sort: sort attributes<commit_after>module.exports = sortByProcedure;

/*
	sort the parts of the passed selector,
	as there is potential for optimization
	(some types of selectors are faster than others)
*/

var ATTRIBUTE = 1;

var procedure = {
    __proto__: null,
    universal: 5, //should be last so that it can be ignored
    tag: 3, //very quick test
    attribute: ATTRIBUTE,
    pseudo: 0, //can be pretty expensive (especially :has)

    //everything else shouldn't be moved
    descendant: -1,
    child: -1,
    parent: -1,
    sibling: -1,
    adjacent: -1
};

var attributes = {
    __proto__: null,
    exists: 8,
    equals: 7,
    not: 6,
    start: 5,
    end: 4,
    any: 3,
    hyphen: 2,
    element: 1
};

function sortByProcedure(arr) {
    for (var i = 1; i < arr.length; i++) {
        var procNew = procedure[arr[i].type];

        if (procNew < 0) continue;

        for (var j = i - 1; j >= 0; j--) {
            if (
                procNew > procedure[arr[j].type] ||
                !(
                    procNew === ATTRIBUTE &&
                    procedure[arr[j].type] === ATTRIBUTE &&
                    attributes[arr[i].action] <= attributes[arr[j].action]
                )
            )
                break;

            var tmp = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = tmp;
        }
    }
    return arr;
}
<|endoftext|>


<commit_before>import { React, PropTypes, styled, useObserver } from 'vendor';
import { StickyTable, Row, Cell } from 'react-sticky-table';
import TutorLink from '../../components/link';
import S from '../../helpers/string';
import { Icon } from 'shared';
import HomeworkQuestions, { ExerciseNumber } from '../../components/homework-questions';
import { colors } from 'theme';
import Loading from 'shared/components/loading-animation';

// https://projects.invisionapp.com/d/main#/console/18937568/403651098/preview

const Wrapper = styled.div`
  margin-top: 4rem;
`;

const ControlsWrapper = styled.div`

`;

const QuestionHeader = ({ ux, styleVariant, label, info }) => useObserver(() => {
  return (
    <>
      <ExerciseNumber variant={styleVariant}>
        {info.hasFreeResponse && (
          <Icon
            type={ux.isShowingFreeResponseForQuestion(info.question) ? 'caret-down' : 'caret-right'}
            onClick={() => ux.toggleFreeResponseForQuestion(info.question)}
          />)}
        {label}
      </ExerciseNumber>
      <ControlsWrapper>{S.numberWithOneDecimalPlace(info.points)} Points</ControlsWrapper>
    </>
  );
});

QuestionHeader.propTypes = {
  styleVariant: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  info:  PropTypes.object.isRequired,
};

const StyledQuestionFreeResonse = styled.div`
  border-bottom: 1px dashed ${colors.neutral.thin};
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  b { margin-right: 1rem; }
`;

const QuestionFreeResponse = ({ ux, info }) => useObserver(() => {
  if (!ux.isShowingFreeResponseForQuestion(info.question)) { return null; }

  return (

      {ux.scores.students.map((student, i) => {
        const studentQuestion = student.questions.find(sq => sq.id == info.question.id);
        return (studentQuestion && studentQuestion.free_response) && (

        );
      })}

  );
});

const StyledStickyTable = styled(StickyTable)`
  .sticky-table-table {
    border: 1px solid ${colors.neutral.pale};
    border-bottom-width: 0;
  }

  .sticky-table-cell, .sticky-table-row {
    vertical-align: middle;
    padding: 0 1.6rem;
    height: 4.1rem;
    border-color: ${colors.neutral.pale};
  }
`;

const Header = styled(Cell)`
  background: ${colors.assignments.submissions.background};
  color: ${colors.neutral.grayblue};
  ${props => props.center && 'text-align: center;'}
`;

const Legend = styled.div`
  margin: 0.8rem 0;
  color: ${colors.neutral.thin};
`;

const Toolbar = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
`;

const Center = styled.div`
  display: flex;
  flex: 1;
  justify-content: center;
  font-size: 1.6rem;
`;

const Right = styled.div`

`;

const GradeButton = styled(TutorLink).attrs({
  to: 'gradeAssignment',
  className: 'btn btn-form-action btn-primary btn-new-flag',
})`
  && {
    padding: 1.2rem 2.1rem 1.6rem 1.1rem;
    line-height: 1.9rem;
  }
`;

const Overview = ({ ux, ux: { planId, scores } }) => useObserver(() => (
  <Wrapper data-test-id="overview">
    <Toolbar>

        This assignment is now open for grading.

      <Right>
        <GradeButton
          params={{ id: planId, courseId: ux.course.id }}
        >
          72 New
          Grade answers
        </GradeButton>
      </Right>
    </Toolbar>

    <Legend>
      MCQ: Multiple Choice Question (auto-graded);
      WRQ: Written Response Question (manually-graded);
      Tutor: Personalized questions assigned by OpenStax Tutor (MCQs & auto-graded)
    </Legend>

    {ux.isExercisesReady ? (
      <HomeworkQuestions
        questionsInfo={scores.questionsInfo}
        questionType="teacher-review"
        headerContentRenderer={(props) => <QuestionHeader ux={ux} {...props} />}
        questionInfoRenderer={(props) => <QuestionFreeResponse ux={ux} {...props} />}
        styleVariant="submission"
      />) : <Loading message="Loading Questions…"/>}

  </Wrapper>
));

Overview.title = 'Submission Overview';
Overview.propTypes = {
  ux: PropTypes.object.isRequired,
};

export default Overview;
<commit_msg>pull in changes from WRM branch<commit_after>import { React, PropTypes, styled, useObserver } from 'vendor';
import { StickyTable, Row, Cell } from 'react-sticky-table';
import { OverlayTrigger, Tooltip } from 'react-bootstrap';
import TutorLink from '../../components/link';
import S from '../../helpers/string';
import { Icon } from 'shared';
import HomeworkQuestions, { ExerciseNumber } from '../../components/homework-questions';
import { colors } from 'theme';
import Loading from 'shared/components/loading-animation';

// https://projects.invisionapp.com/d/main#/console/18937568/403651098/preview

const Wrapper = styled.div`
  margin-top: 4rem;
`;

const ControlsWrapper = styled.div`

`;

const QuestionHeader = ({ ux, styleVariant, label, info }) => useObserver(() => {
  return (
    <>
      <ExerciseNumber variant={styleVariant}>
        {info.hasFreeResponse && (
          <Icon
            type={ux.isShowingFreeResponseForQuestion(info.question) ? 'caret-down' : 'caret-right'}
            onClick={() => ux.toggleFreeResponseForQuestion(info.question)}
          />)}
        {label}
      </ExerciseNumber>
      <ControlsWrapper>{S.numberWithOneDecimalPlace(info.points)} Points</ControlsWrapper>
    </>
  );
});

QuestionHeader.propTypes = {
  styleVariant: PropTypes.string.isRequired,
  label: PropTypes.string.isRequired,
  info:  PropTypes.object.isRequired,
};

const StyledQuestionFreeResonse = styled.div`
  border-bottom: 1px dashed ${colors.neutral.thin};
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  b { margin-right: 1rem; }
`;

const QuestionFreeResponse = ({ ux, info }) => useObserver(() => {
  if (!ux.isShowingFreeResponseForQuestion(info.question)) { return null; }

  return (

      {ux.scores.students.map((student, i) => {
        const studentQuestion = student.questions.find(sq => sq.id == info.question.id);
        return (studentQuestion && studentQuestion.free_response) && (

        );
      })}

  );
});

const StyledStickyTable = styled(StickyTable)`
  .sticky-table-table {
    border: 1px solid ${colors.neutral.pale};
    border-bottom-width: 0;
  }

  .sticky-table-cell, .sticky-table-row {
    vertical-align: middle;
    padding: 0 1.6rem;
    height: 4.1rem;
    border-color: ${colors.neutral.pale};
  }
`;

const Header = styled(Cell)`
  background: ${colors.assignments.submissions.background};
  color: ${colors.neutral.grayblue};
  ${props => props.center && 'text-align: center;'}
`;

const Legend = styled.div`
  margin: 0.8rem 0;
  color: ${colors.neutral.thin};
`;

const Toolbar = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2rem;
`;

const Center = styled.div`
  display: flex;
  flex: 1;
  justify-content: center;
  font-size: 1.6rem;
`;

const Right = styled.div`

`;

const GradeButton = styled(TutorLink).attrs({
  to: 'gradeAssignment',
  className: 'btn btn-form-action btn-primary btn-new-flag',
})`
  && {
    padding: 1.2rem 2.1rem 1.6rem 1.1rem;
    line-height: 1.9rem;
  }
`;

const StyledTooltip = styled(Tooltip)`
  max-width: 30rem;
  &.tooltip.show { opacity: 1; }

  .tooltip-inner {
    padding: 2.2rem 1.6rem;
    text-align: left;
  }
`;

const AvailablePoints = ({ value }) => {
  if (!value) {
    return (
      <OverlayTrigger
        placement="right"
        overlay={

        }
      >
        <Icon variant="infoCircle" />
      </OverlayTrigger>
    );
  }
  return (
    ({S.numberWithOneDecimalPlace(value)})
  );
};
AvailablePoints.propTypes = {
  value: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string,
  ]),
};

const Overview = ({ ux, ux: { scores } }) => {
  return useObserver(() => (
    <Wrapper data-test-id="overview">
      <Toolbar>

          This assignment is now open for grading.

        <Right>
          <GradeButton variant="primary" className="btn-new-flag">
            72 New
            Grade answers
          </GradeButton>
        </Right>
      </Toolbar>

      <Legend>
        MCQ: Multiple Choice Question (auto-graded);
        WRQ: Written Response Question (manually-graded);
        Tutor: Personalized questions assigned by OpenStax Tutor (MCQs & auto-graded)
      </Legend>

      {ux.isExercisesReady ? (
        <HomeworkQuestions
          questionsInfo={scores.questionsInfo}
          questionType="teacher-review"
          headerContentRenderer={(props) => <QuestionHeader ux={ux} {...props} />}
          questionInfoRenderer={(props) => <QuestionFreeResponse ux={ux} {...props} />}
          styleVariant="submission"
        />) : <Loading message="Loading Questions…"/>}

    </Wrapper>
  ));
};
Overview.title = 'Submission Overview';
Overview.propTypes = {
  ux: PropTypes.object.isRequired,
};

export default Overview;
<|endoftext|>