<commit_before>
import React, { Component } from 'react';
import { TouchableOpacity,Alert,ListView,View,Text } from 'react-native';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, List, ListItem, InputGroup, Input, Picker, Thumbnail ,Footer,FooterTab,Card,CardItem } from 'native-base';

import ProgressBarClassic from 'react-native-progress-bar-classic';

import { Grid, Row } from 'react-native-easy-grid';

import { openDrawer } from '../../actions/drawer';
import { setIndex } from '../../actions/list';
import myTheme from '../../themes/base-theme';
import styles from './styles';

const delete_ = 'http://192.168.2.82/usave/delete.php';
const Server_getaccountinfo = 'http://192.168.2.82/usave/accountinfo.php';
const server_plans = 'http://192.168.2.82/usave/plan.php';
const server_newplans = 'http://192.168.2.82/usave/newplan.php';
const server_scatter = 'http://192.168.2.82/usave/scatter.php';

const {
  reset,
  pushRoute,
} = actions;

class Home extends Component {

  static propTypes = {
    name: React.PropTypes.string,
    list: React.PropTypes.arrayOf(React.PropTypes.string),
    setIndex: React.PropTypes.func,
    openDrawer: React.PropTypes.func,
    pushRoute: React.PropTypes.func,
    reset: React.PropTypes.func,
    navigation: React.PropTypes.shape({
      key: React.PropTypes.string,
    }),
  }

  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      tab1: false,
      tab2: false,
      tab3: false,
      tab4: true,
      tab: 'Home',
      bal: '',
      salary: '',
      pa_bal: '',
      pid: '',
      n_pid: '',
      n_palot: '',
      n_ptotal: '',
      n_pname: '',
      dataSource: ds.cloneWithRows([
            'row 1', 'row2'
         ])

    };

    this.getAccountinfo();

  }

  toggleTab1() {
    this.setState({
      tab1: true,
      tab2: false,
      tab3: false,
      tab4: false,
      tab: 'Plans'
    });
    this.getplans();

  }

  toggleTab2() {
    this.setState({
      tab1: false,
      tab2: true,
      tab3: false,
      tab4: false,
      tab: 'Profile'
    });
  }

  toggleTab3() {
    this.setState({
      tab1: false,
      tab2: false,
      tab3: true,
      tab4: false,
      tab: 'Settings'
    });
  }

  toggleTab4() {
    this.setState({
      tab1: false,
      tab2: false,
      tab3: false,
      tab4: true,
      tab: 'Home'

    });
    this.getAccountinfo();
  }
  toggleTab5() {
    this.setState({
      tab1: true,
      tab2: false,
      tab3: false,
      tab4: false,
      tab: 'Add Plan'

    });
  }

  pushRoute(route, index) {
    this.props.setIndex(index);
    this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key);
  }

  // render value

    renderContent() {

    const { tab } = this.state
    let content
    switch(tab) {
      case 'Home':
         content = <View>
                      <Card>
                       <CardItem style={{backgroundColor: '#9b7bb5'}}>
                       <List>
                       <ListItem iconLeft>
                       <Icon name="ios-power" style={{ color: '#9b7bb5' }} />
                          <Text style={styles.bal}>Savings Account</Text>
                          <Text note style={styles.amount}>{this.state.bal}</Text>
                        </ListItem>
                        </List>
                      </CardItem>
                      <CardItem style={{backgroundColor: '#6bb3b5'}}>
                      <List>
                       <ListItem iconLeft>
                       <Icon name="ios-power" style={{ color: '#6bb3b5' }} />
                          <Text style={styles.bal}>Monthly Salary</Text>
                          <Text note style={styles.amount}>{this.state.pa_bal}</Text>
                        </ListItem>
                        </List>
                      </CardItem>
                      <CardItem style={{backgroundColor: '#81b64c'}}>
                      <List>
                       <ListItem iconLeft>
                       <Icon name="ios-power" style={{ color: '#81b64c' }} />
                          <Text style={styles.bal}>Unbudget Balance</Text>
                          <Text note style={styles.amount}>{this.state.salary}</Text>
                        </ListItem>
                        </List>
                        <Button block style={{ marginBottom: 20, marginRight: 50, marginLeft: 50}}>Distribute</Button>
                      </CardItem>
                      </Card>
                    </View>

        break
      case 'Plans':
        content =  <View>

       <View style={{}}>

      </View>
           <ListView
            style = {styles.listContainer}
            dataSource = {this.state.dataSource}
            renderRow = {this.renderRow}
         />
         </View>
        break
      case 'Profile':
        content = <Text>This is the content Profile</Text>
        break
      case 'Settings':
        content = <Text>This is the content Settings</Text>
        break
      case 'Add Plan':
      content =
                  <View style={{margin: 20, backgroundColor: 'white'}}>
                     <List>
                        <ListItem style={{padding: 20}}>
                            <InputGroup >
                                <Input inlineLabel label="Plan Name" onChangeText={(e) => this.setState({n_pname:e})}/>
                            </InputGroup>
                        </ListItem>

                        <ListItem style={{padding: 10}}>
                            <InputGroup>
                                <Icon name="ios-clipboard-outline" style={{ color: 'blue' }} />
                                <Input inlineLabel label="Money Allot" placeholder="Money Allot" onChangeText={(e) => this.setState({n_palot:e})} />
                            </InputGroup>
                        </ListItem>
                        <ListItem style={{padding: 10}}>
                            <InputGroup>
                                <Icon name="ios-clipboard-outline" style={{ color: 'blue' }} />
                                <Input inlineLabel label="Total Amount" placeholder="Total Amount" onChangeText={(e) => this.setState({n_ptotal:e})}/>
                            </InputGroup>
                        </ListItem>
                        <Button block style={{backgroundColor: '#250f59', marginTop: 130, marginBottom: 20, marginRight: 50, marginLeft: 50}} onPress={()=>this.toggleTab1()}>Cancel</Button>
                        <Button block style={{backgroundColor: '#250f59', marginBottom: 20, marginRight: 50, marginLeft: 50}} onPress={()=>this.newplan()}>Save</Button>
                    </List>
                  </View>
      break
    }

    return content

  }

   renderTitle() {
    const { tab } = this.state
    let title
    switch(tab) {
      case 'Home':
         title = <Title>Home</Title>
        break
      case 'Plans':
        title = <Title>Plans</Title>
        break
      case 'Profile':
        title =  <Title>Profile</Title>
        break
      case 'Settings':
        title = <Title>Settings</Title>
        break
      case 'Add Plan':
        title = <Title>Add Plan</Title>
        break
    }

    return title

  }

  //delete plans
  deleteplant(e){

    fetch(delete_ + '?plan_id=' + this.state.pid )
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        if (emessage === '0') {

          Alert.alert("Delete failed",'Deletion failed',[
        {text: 'Ok', onPress: () => this.toggleTab1()},

        ]);

        }

        else {
             Alert.alert("Delete successful",'Successfully deleted',[
        {text: 'Ok', onPress: () => this.toggleTab1()},

        ]);

        }

      })

      .done();

  }

  //scatter.php
  startbudget(){

    fetch(server_scatter + '?acc_no=' + this.props.name + '&p_salary=' + this.state.salary)
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
         Alert.alert('','Distribution Successfully');

      })
      .done();

  }

  //new plan
  newplan(){
    fetch(server_newplans + '?acc_no=' + this.props.name + '&pname=' + this.state.n_pname + '&pmoneyalot=' + this.state.n_palot + '&ptotal=' + this.state.n_ptotal)
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        Alert.alert('','Plan Created Successfully');

         })
        .done();

  }

  //render plans
  renderRow(row) {
  return (

      <Content style={{}}>

      <Card style={{marginLeft: 15, marginRight: 15, marginTop: 5 , marginBottom: 1}}>
      <View style={styles.plan}>
      <CardItem>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-clipboard-outline" style={{ color: 'blue' }} />
      <Text style={{color:'black',marginLeft:10,marginRight:10,fontSize:30}}>{row.p_name}</Text>
      <TouchableOpacity onPress={() =>
      fetch(delete_ + '?plan_id=' + row.pid )
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        if (emessage === '0') {

          Alert.alert("Delete failed",'Deletion failed');

        }

        else {

             Alert.alert("Delete successful",'Successfully deleted');
        }

      })

      .done()} ><Text style={{color: 'red', fontSize: 25}}> x </Text></TouchableOpacity>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Alloted:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_money_alot}%</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Goal:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_total}</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Saved:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_saved}</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Amount Left:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.kulang}</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Months Left:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_month}</Text>
      </ListItem>
      </List>
      <View style={{padding: 10}}>
      <ProgressBarClassic label="Label" progress={row.percent}/>
      </View>
      </CardItem>
      </View>
      </Card>

      </Content>

  );
}

  // Account info
  getAccountinfo(){

    fetch(Server_getaccountinfo + '?acc_no=' + this.props.name)
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        this.setState({bal: responseData.balance});
        this.setState({salary: responseData.salary});
        this.setState({pa_bal: responseData.pa_balance});

         })
        .done();

  }
  // Plans
  getplans(){

    fetch(server_plans + '?acc_no=' + this.props.name)
      .then((response) => response.json())
      .then((responseData) => {

        for (var i = 0; i < responseData.length; i++)
          {
              this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData)});
          }

        })
        .done();

  }

  render() {
    return (

      <Container theme={myTheme} style={styles.container}>
         <Header>
          <Button transparent onPress={() => this.props.reset(this.props.navigation.key)}>
            <Icon name="ios-power" />
          </Button>

          {this.renderTitle()}
          <Button transparent onPress={() => this.toggleTab5()}>
            <Text style={{fontSize:60}}>+</Text>
          </Button>
        </Header>

        <Content>

          {this.renderContent()}

          </Content>

        <Footer >
          <FooterTab>
          <Button active={this.state.tab4} onPress={() => this.toggleTab4()} >
                Home
              <Icon name="ios-home-outline" />
            </Button>
            <Button active={this.state.tab1} onPress={() => this.toggleTab1()} >
                Plans
              <Icon name="ios-clipboard-outline" />
            </Button>
            <Button active={this.state.tab2} onPress={() => this.toggleTab2()} >
                Profile
              <Icon name="ios-person-outline" />
            </Button>
            <Button active={this.state.tab3} onPress={() => this.toggleTab3()} >
                Settings
              <Icon name="ios-paper-outline" />
            </Button>

          </FooterTab>
        </Footer>
      </Container>

    );
  }
}

function bindAction(dispatch) {
  return {
    setIndex: index => dispatch(setIndex(index)),
    openDrawer: () => dispatch(openDrawer()),
    pushRoute: (route, key) => dispatch(pushRoute(route, key)),
    reset: key => dispatch(reset([{ key: 'login' }], key, 0)),
  };
}

const mapStateToProps = state => ({
  name: state.user.name,
  list: state.list.list,
  navigation: state.cardNavigation,
});

export default connect(mapStateToProps, bindAction)(Home);
<commit_msg>Update index file<commit_after>
import React, { Component } from 'react';
import { TouchableOpacity,Alert,ListView,View,Text } from 'react-native';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, List, ListItem, InputGroup, Input, Picker, Thumbnail ,Footer,FooterTab,Card,CardItem } from 'native-base';

import ProgressBarClassic from 'react-native-progress-bar-classic';

import { Grid, Row } from 'react-native-easy-grid';

import { openDrawer } from '../../actions/drawer';
import { setIndex } from '../../actions/list';
import myTheme from '../../themes/base-theme';
import styles from './styles';

const delete_ = 'http://192.168.2.82/usave/delete.php';
const Server_getaccountinfo = 'http://192.168.2.82/usave/accountinfo.php';
const server_plans = 'http://192.168.2.82/usave/plan.php';
const server_newplans = 'http://192.168.2.82/usave/newplan.php';
const server_scatter = 'http://192.168.2.82/usave/scatter.php';

const {
  reset,
  pushRoute,
} = actions;

class Home extends Component {

  static propTypes = {
    name: React.PropTypes.string,
    list: React.PropTypes.arrayOf(React.PropTypes.string),
    setIndex: React.PropTypes.func,
    openDrawer: React.PropTypes.func,
    pushRoute: React.PropTypes.func,
    reset: React.PropTypes.func,
    navigation: React.PropTypes.shape({
      key: React.PropTypes.string,
    }),
  }

  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      tab1: false,
      tab2: false,
      tab3: false,
      tab4: true,
      tab: 'Home',
      bal: '',
      salary: '',
      pa_bal: '',
      pid: '',
      n_pid: '',
      n_palot: '',
      n_ptotal: '',
      n_pname: '',
      dataSource: ds.cloneWithRows([
            'row 1', 'row2'
         ])

    };

    this.getAccountinfo();

  }

  toggleTab1() {
    this.setState({
      tab1: true,
      tab2: false,
      tab3: false,
      tab4: false,
      tab: 'Plans'
    });
    this.getplans();

  }

  toggleTab2() {
    this.setState({
      tab1: false,
      tab2: true,
      tab3: false,
      tab4: false,
      tab: 'Profile'
    });
  }

  toggleTab3() {
    this.setState({
      tab1: false,
      tab2: false,
      tab3: true,
      tab4: false,
      tab: 'Settings'
    });
  }

  toggleTab4() {
    this.setState({
      tab1: false,
      tab2: false,
      tab3: false,
      tab4: true,
      tab: 'Home'

    });
    this.getAccountinfo();
  }
  toggleTab5() {
    this.setState({
      tab1: true,
      tab2: false,
      tab3: false,
      tab4: false,
      tab: 'Add Plan'

    });
  }

  pushRoute(route, index) {
    this.props.setIndex(index);
    this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key);
  }

  // render value

    renderContent() {

    const { tab } = this.state
    let content
    switch(tab) {
      case 'Home':
         content = <View>
                      <Card>
                       <CardItem style={{backgroundColor: '#9b7bb5'}}>
                       <List>
                       <ListItem iconLeft>
                       <Icon name="ios-power" style={{ color: '#9b7bb5' }} />
                          <Text style={styles.bal}>Savings Account</Text>
                          <Text note style={styles.amount}>{this.state.bal}</Text>
                        </ListItem>
                        </List>
                      </CardItem>
                      <CardItem style={{backgroundColor: '#6bb3b5'}}>
                      <List>
                       <ListItem iconLeft>
                       <Icon name="ios-power" style={{ color: '#6bb3b5' }} />
                          <Text style={styles.bal}>Monthly Salary</Text>
                          <Text note style={styles.amount}>{this.state.pa_bal}</Text>
                        </ListItem>
                        </List>
                      </CardItem>
                      <CardItem style={{backgroundColor: '#81b64c'}}>
                      <List>
                       <ListItem iconLeft>
                       <Icon name="ios-power" style={{ color: '#81b64c' }} />
                          <Text style={styles.bal}>Unbudget Balance</Text>
                          <Text note style={styles.amount}>{this.state.salary}</Text>
                        </ListItem>
                        </List>
                        <Button block style={{ marginBottom: 20, marginRight: 50, marginLeft: 50}}>Distribute</Button>
                      </CardItem>
                      </Card>
                    </View>

        break
      case 'Plans':
        content =  <View>

       <View style={{}}>

      </View>
           <ListView
            style = {styles.listContainer}
            dataSource = {this.state.dataSource}
            renderRow = {this.renderRow}
         />
         </View>
        break
      case 'Profile':
        content = <Text>This is the content Profile</Text>
        break
      case 'Settings':
        content = <Text>This is the content Settings</Text>
        break
      case 'Add Plan':
      content =
                  <View style={{margin: 20, backgroundColor: 'white'}}>
                     <List>
                        <ListItem style={{padding: 20}}>
                            <InputGroup >
                                <Input inlineLabel label="Plan Name" onChangeText={(e) => this.setState({n_pname:e})}/>
                            </InputGroup>
                        </ListItem>

                        <ListItem style={{padding: 10}}>
                            <InputGroup>
                                <Icon name="ios-clipboard-outline" style={{ color: 'blue' }} />
                                <Input inlineLabel label="Money Allot" placeholder="Percent" onChangeText={(e) => this.setState({n_palot:e})} />
                            </InputGroup>
                        </ListItem>
                        <ListItem style={{padding: 10}}>
                            <InputGroup>
                                <Icon name="ios-clipboard-outline" style={{ color: 'blue' }} />
                                <Input inlineLabel label="Total Amount" placeholder="Total Amount" onChangeText={(e) => this.setState({n_ptotal:e})}/>
                            </InputGroup>
                        </ListItem>
                        <Button block style={{backgroundColor: '#250f59', marginTop: 130, marginBottom: 20, marginRight: 50, marginLeft: 50}} onPress={()=>this.toggleTab1()}>Cancel</Button>
                        <Button block style={{backgroundColor: '#250f59', marginBottom: 20, marginRight: 50, marginLeft: 50}} onPress={()=>this.newplan()}>Save</Button>
                    </List>
                  </View>
      break
    }

    return content

  }

   renderTitle() {
    const { tab } = this.state
    let title
    switch(tab) {
      case 'Home':
         title = <Title>Home</Title>
        break
      case 'Plans':
        title = <Title>Plans</Title>
        break
      case 'Profile':
        title =  <Title>Profile</Title>
        break
      case 'Settings':
        title = <Title>Settings</Title>
        break
      case 'Add Plan':
        title = <Title>Add Plan</Title>
        break
    }

    return title

  }

  //delete plans
  deleteplant(e){

    fetch(delete_ + '?plan_id=' + this.state.pid )
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        if (emessage === '0') {

          Alert.alert("Delete failed",'Deletion failed',[
        {text: 'Ok', onPress: () => this.toggleTab1()},

        ]);

        }

        else {
             Alert.alert("Delete successful",'Successfully deleted',[
        {text: 'Ok', onPress: () => this.toggleTab1()},

        ]);

        }

      })

      .done();

  }

  //scatter.php
  startbudget(){

    fetch(server_scatter + '?acc_no=' + this.props.name + '&p_salary=' + this.state.salary)
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
         Alert.alert('','Distribution Successfully');

      })
      .done();

  }

  //new plan
  newplan(){
    fetch(server_newplans + '?acc_no=' + this.props.name + '&pname=' + this.state.n_pname + '&pmoneyalot=' + this.state.n_palot + '&ptotal=' + this.state.n_ptotal)
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        Alert.alert('','Plan Created Successfully');

         })
        .done();

  }

  //render plans
  renderRow(row) {
  return (

      <Content style={{}}>

      <Card style={{marginLeft: 15, marginRight: 15, marginTop: 5 , marginBottom: 1}}>
      <View style={styles.plan}>
      <CardItem>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-clipboard-outline" style={{ color: 'blue' }} />
      <Text style={{color:'black',marginLeft:10,marginRight:10,fontSize:30}}>{row.p_name}</Text>
      <TouchableOpacity onPress={() =>
      fetch(delete_ + '?plan_id=' + row.pid )
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        if (emessage === '0') {

          Alert.alert("Delete failed",'Deletion failed');

        }

        else {

             Alert.alert("Delete successful",'Successfully deleted');
        }

      })

      .done()} ><Text style={{color: 'red', fontSize: 25}}> x </Text></TouchableOpacity>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Alloted:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_money_alot}%</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Goal:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_total}</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Saved:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_saved}</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Amount Left:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.kulang}</Text>
      </ListItem>
      </List>

      <List>
      <ListItem iconLeft>
      <Icon name="ios-power" style={{ color: '#FFF' }} />
      <Text style={{color:'black',marginRight:10,fontSize:20}}>Months Left:</Text>
      <Text note style={{color:'black',fontSize:20}}>{row.p_month}</Text>
      </ListItem>
      </List>
      <View style={{padding: 10}}>
      <ProgressBarClassic label="Label" progress={row.percent}/>
      </View>
      </CardItem>
      </View>
      </Card>

      </Content>

  );
}

  // Account info
  getAccountinfo(){

    fetch(Server_getaccountinfo + '?acc_no=' + this.props.name)
      .then((response) => response.json())
      .then((responseData) => {
        const emessage = responseData.emessage;
        this.setState({bal: responseData.balance});
        this.setState({salary: responseData.salary});
        this.setState({pa_bal: responseData.pa_balance});

         })
        .done();

  }
  // Plans
  getplans(){

    fetch(server_plans + '?acc_no=' + this.props.name)
      .then((response) => response.json())
      .then((responseData) => {

        for (var i = 0; i < responseData.length; i++)
          {
              this.setState({ dataSource: this.state.dataSource.cloneWithRows(responseData)});
          }

        })
        .done();

  }

  render() {
    return (

      <Container theme={myTheme} style={styles.container}>
         <Header>
          <Button transparent onPress={() => this.props.reset(this.props.navigation.key)}>
            <Icon name="ios-power" />
          </Button>

          {this.renderTitle()}
          <Button transparent onPress={() => this.toggleTab5()}>
            <Text style={{fontSize:60}}>+</Text>
          </Button>
        </Header>

        <Content>

          {this.renderContent()}

          </Content>

        <Footer >
          <FooterTab>
          <Button active={this.state.tab4} onPress={() => this.toggleTab4()} >
                Home
              <Icon name="ios-home-outline" />
            </Button>
            <Button active={this.state.tab1} onPress={() => this.toggleTab1()} >
                Plans
              <Icon name="ios-clipboard-outline" />
            </Button>
            <Button active={this.state.tab2} onPress={() => this.toggleTab2()} >
                Profile
              <Icon name="ios-person-outline" />
            </Button>
            <Button active={this.state.tab3} onPress={() => this.toggleTab3()} >
                Settings
              <Icon name="ios-paper-outline" />
            </Button>

          </FooterTab>
        </Footer>
      </Container>

    );
  }
}

function bindAction(dispatch) {
  return {
    setIndex: index => dispatch(setIndex(index)),
    openDrawer: () => dispatch(openDrawer()),
    pushRoute: (route, key) => dispatch(pushRoute(route, key)),
    reset: key => dispatch(reset([{ key: 'login' }], key, 0)),
  };
}

const mapStateToProps = state => ({
  name: state.user.name,
  list: state.list.list,
  navigation: state.cardNavigation,
});

export default connect(mapStateToProps, bindAction)(Home);
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const ReactDOM = require('react-dom')
const ImmutableComponent = require('./immutableComponent')
const Tab = require('./tab')
const windowActions = require('../actions/windowActions')
const appActions = require('../actions/appActions')
const siteTags = require('../constants/siteTags')
const dragTypes = require('../constants/dragTypes')
const siteUtil = require('../state/siteUtil')
const dnd = require('../dnd')
const dndData = require('../dndData')

class PinnedTabs extends ImmutableComponent {
  onDrop (e) {
    const clientX = e.clientX
    // This must be executed async because the state change that this causes
    // will cause the onDragEnd to never run
    setTimeout(() => {
      const sourceDragData = dndData.getDragData(e.dataTransfer, dragTypes.TAB)
      const key = sourceDragData.get('key')
      let droppedOnTab = dnd.closestFromXOffset(this.tabRefs.filter(tab => tab && tab.props.frameProps.get('key') !== key), clientX).selectedRef
      if (droppedOnTab) {
        const isLeftSide = dnd.isLeftSide(ReactDOM.findDOMNode(droppedOnTab), clientX)
        const droppedOnFrameProps = this.props.frames.find(frame => frame.get('key') === droppedOnTab.props.frameProps.get('key'))
        windowActions.moveTab(sourceDragData, droppedOnFrameProps, isLeftSide)
        if (!sourceDragData.get('pinnedLocation')) {
          windowActions.setPinned(sourceDragData, true)
          appActions.addSite(sourceDragData, siteTags.PINNED)
        } else {
          appActions.moveSite(siteUtil.getDetailFromFrame(sourceDragData, siteTags.PINNED),
            siteUtil.getDetailFromFrame(droppedOnFrameProps, siteTags.PINNED),
            isLeftSide)
        }
      }
    }, 0)
  }

  onDragOver (e) {
    e.dataTransfer.dropEffect = 'move'
    e.preventDefault()
  }

  render () {
    this.tabRefs = []
    return

       {
          this.props.frames
            .filter(frameProps => frameProps.get('pinnedLocation'))
            .map(frameProps =>
                <Tab activeDraggedTab={this.props.tabs.get('activeDraggedTab')}
                  ref={node => this.tabRefs.push(node)}
                  draggingOverData={this.props.draggingOverData}
                  frameProps={frameProps}
                  frames={this.props.frames}
                  key={'tab-' + frameProps.get('key')}
                  paintTabs={this.props.paintTabs}
                  previewTabs={this.props.previewTabs}
                  isActive={this.props.activeFrame === frameProps}
                  isPrivate={frameProps.get('isPrivate')}
                  partOfFullPageSet={this.props.partOfFullPageSet}/>)
      }

  }
}

module.exports = PinnedTabs
<commit_msg>Fix pinned tag regression with undefined dataTransfer<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const ReactDOM = require('react-dom')
const ImmutableComponent = require('./immutableComponent')
const Tab = require('./tab')
const windowActions = require('../actions/windowActions')
const appActions = require('../actions/appActions')
const siteTags = require('../constants/siteTags')
const dragTypes = require('../constants/dragTypes')
const siteUtil = require('../state/siteUtil')
const dnd = require('../dnd')
const dndData = require('../dndData')

class PinnedTabs extends ImmutableComponent {
  onDrop (e) {
    const clientX = e.clientX
    const sourceDragData = dndData.getDragData(e.dataTransfer, dragTypes.TAB)

    // This must be executed async because the state change that this causes
    // will cause the onDragEnd to never run
    setTimeout(() => {
      const key = sourceDragData.get('key')
      let droppedOnTab = dnd.closestFromXOffset(this.tabRefs.filter(tab => tab && tab.props.frameProps.get('key') !== key), clientX).selectedRef
      if (droppedOnTab) {
        const isLeftSide = dnd.isLeftSide(ReactDOM.findDOMNode(droppedOnTab), clientX)
        const droppedOnFrameProps = this.props.frames.find(frame => frame.get('key') === droppedOnTab.props.frameProps.get('key'))
        windowActions.moveTab(sourceDragData, droppedOnFrameProps, isLeftSide)
        if (!sourceDragData.get('pinnedLocation')) {
          windowActions.setPinned(sourceDragData, true)
          appActions.addSite(sourceDragData, siteTags.PINNED)
        } else {
          appActions.moveSite(siteUtil.getDetailFromFrame(sourceDragData, siteTags.PINNED),
            siteUtil.getDetailFromFrame(droppedOnFrameProps, siteTags.PINNED),
            isLeftSide)
        }
      }
    }, 0)
  }

  onDragOver (e) {
    e.dataTransfer.dropEffect = 'move'
    e.preventDefault()
  }

  render () {
    this.tabRefs = []
    return

       {
          this.props.frames
            .filter(frameProps => frameProps.get('pinnedLocation'))
            .map(frameProps =>
                <Tab activeDraggedTab={this.props.tabs.get('activeDraggedTab')}
                  ref={node => this.tabRefs.push(node)}
                  draggingOverData={this.props.draggingOverData}
                  frameProps={frameProps}
                  frames={this.props.frames}
                  key={'tab-' + frameProps.get('key')}
                  paintTabs={this.props.paintTabs}
                  previewTabs={this.props.previewTabs}
                  isActive={this.props.activeFrame === frameProps}
                  isPrivate={frameProps.get('isPrivate')}
                  partOfFullPageSet={this.props.partOfFullPageSet}/>)
      }

  }
}

module.exports = PinnedTabs
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'AddRowView',
  package: 'foam.ui.md',
  extendsModel: 'View',
  traits: ['PositionedDOMViewTrait', 'VerticalScrollNativeTrait'],

  requires: [
    'foam.ui.md.ToolbarCSS'
  ],

  imports: [
    'queryFactory',
    'stack'
  ],

  exports: [
    'selection$'
  ],

  models: [
    {
      model_: 'Model',
      name: 'SingleEntryHidingDAO',
      extendsModel: 'ProxyDAO',
      methods: {
        select: function(sink, options) {
          var firstEntry;
          var seen = 0;
          sink = sink || [];
          var mySink = {
            put: sink && sink.put && function(x) {
              seen++;
              if (seen === 1) {
                firstEntry = x;
              } else if (seen === 2) {
                sink.put(firstEntry);
                sink.put(x);
              } else {
                sink.put(x);
              }
            },
            error: sink && sink.error && sink.error.bind(sink),
            eof: sink && sink.eof && sink.eof.bind(sink)
          };

          return this.delegate.select(mySink, options);
        }
      }
    }
  ],

  properties: [
    {
      model_: 'ViewFactoryProperty',
      name: 'rowView',
      defaultValue: 'foam.ui.md.TextFieldView'
    },
    {
      name: 'data'
    },
    {
      name: 'softData',
      documentation: 'The object currently under consideration.',
      factory: function() {
        this.dao.find(this.data, {
          put: function(x) { debugger; this.softData = x; }.bind(this)
        });
        return '';
      },
      postSet: function(old, nu) {
        if (nu) {
          this.q = this.objectToQuery(nu);
          this.selected = true;
        }
      }
    },
    {
      name: 'q',
      label: 'Search',
      view: {
        factory_: 'foam.ui.md.TextFieldView',
        onKeyMode: true,
        floatingLabel: false
      },
      postSet: function(old, nu) {
        this.selected = false;
      }
    },
    {
      name: 'selected'
    },
    {
      name: 'subType',
      documentation: 'Based on ReferenceProperty, the name of the type.'
    },
    {
      name: 'subKey',
      documentation: 'The mLang expression for looking up the key from a ' +
          'whole object. Defaults to .ID',
      factory: function() {
        return FOAM.lookup(this.subType, this.X).ID;
      }
    },
    {
      model_: 'DAOProperty',
      name: 'dao',
      documentation: 'The DAO used to look up the models. Defaults to ' +
          'mySubTypeDAO for subType == "MySubType".',
      factory: function() {
        var name = this.subType[0].toLowerCase() + this.subType.substring(1);
        var daoName = name + 'DAO';
        return this.X[daoName];
      }
    },
    {
      name: 'wrappedDAO',
      factory: function() {
        console.log('hide on single', this.hideListOnSingle);
        return this.hideListOnSingle ?
            this.SingleEntryHidingDAO.create({ delegate: this.dao }) : this.dao;
      }
    },
    {
      model_: 'DAOProperty',
      name: 'filteredDAO',
      dynamicValue: function() {
        this.q; this.wrappedDAO; this.limit;
        var q = this.q ? this.queryFactory(this.q) : TRUE;
        var dao = this.wrappedDAO.where(q).limit(this.limit);
        return dao;
      },
      view: {
        factory_: 'DAOListView',
        className: 'rows',
        tagName: 'div',
        useSelection: true
      }
    },
    {
      name: 'queryFactory',
      defaultValue: function(q) { return STARTS_WITH_IC(this.subKey, q); }
    },
    {
      name: 'objectToQuery',
      documentation: 'Turns an object from the DAO into a query string.',
      factory: function() {
        return function(obj) { return this.subKey.f(obj); }.bind(this);
      }
    },
    {
      // TODO: DAO should be pre-limited instead
      name: 'limit',
      defaultValue: 40
    },
    {
      name: 'className',
      defaultValue: 'AddRowView'
    },
    {
      name: 'bodyId',
      factory: function() { return this.nextID(); }
    },
    {
      name: 'scrollerID',
      factory: function() { return this.nextID(); }
    },
    {
      name: 'hideListOnSingle',
      documentation: 'When true (the default), the suggestion list disappears when there is only one match. When false it is always visible.',
      defaultValue: true
    },
    {
      name: 'returnOnSelect',
      documentation: 'When true, updates $$DOC{ref:".data"} and returns when ' +
          'the user chooses an entry. When false, the query is updated to ' +
          'match the selected row.',
      defaultValue: true
    },
    {
      name: 'selection',
      postSet: function(old, nu) {
        if (nu) {
          if (this.returnOnSelect) {
            this.data = this.subKey.f(nu);
            this.doClose();
          } else {
            this.softData = nu;
          }
        }
      }
    }
  ],

  templates: [
    function CSS() {/*
      .AddRowView {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
        background: #fff;
        overflow: hidden;
      }
      .AddRowView .arvBody {
        flex-grow: 1;
        overflow-y: auto;
      }
      .AddRowView .rows {
        width: 100%;
        border: none;
      }
      .AddRowView .rows-row {
        padding: 0 12px 0 16px;
      }
    */},
    function toInnerHTML() {/*

        $$cancel $$accept
        $$q{ extraClassName: 'grow', clearAction: true }

        $$filteredDAO{ rowView: this.rowView }

    */}
  ],

  methods: {
    doClose: function() {
      // Don't close twice.
      if ( this.closed_ ) return;
      this.closed_ = true;

      this.stack.back();
    }
  },

  actions: [
    {
      name: 'cancel',
      label: '',
      iconUrl: 'images/ic_clear_24dp.png',
      isAvailable: function() { return !this.selected; },
      action: function() {
        this.doClose();
      }
    },
    {
      name: 'accept',
      label: '',
      iconUrl: 'images/ic_done_24dp.png',
      keyboardShortcuts: [ 13 /* enter */ ],
      isAvailable: function() { return this.selected; },
      action: function() {
        this.data = this.softData;
        this.doClose();
      }
    }
  ]
});
<commit_msg>AddRowView: Fix softData handling bugs<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'AddRowView',
  package: 'foam.ui.md',
  extendsModel: 'View',
  traits: ['PositionedDOMViewTrait', 'VerticalScrollNativeTrait'],

  requires: [
    'foam.ui.md.ToolbarCSS'
  ],

  imports: [
    'queryFactory',
    'stack'
  ],

  exports: [
    'selection$'
  ],

  models: [
    {
      model_: 'Model',
      name: 'SingleEntryHidingDAO',
      extendsModel: 'ProxyDAO',
      methods: {
        select: function(sink, options) {
          var firstEntry;
          var seen = 0;
          sink = sink || [];
          var mySink = {
            put: sink && sink.put && function(x) {
              seen++;
              if (seen === 1) {
                firstEntry = x;
              } else if (seen === 2) {
                sink.put(firstEntry);
                sink.put(x);
              } else {
                sink.put(x);
              }
            },
            error: sink && sink.error && sink.error.bind(sink),
            eof: sink && sink.eof && sink.eof.bind(sink)
          };

          return this.delegate.select(mySink, options);
        }
      }
    }
  ],

  properties: [
    {
      model_: 'ViewFactoryProperty',
      name: 'rowView',
      defaultValue: 'foam.ui.md.TextFieldView'
    },
    {
      name: 'data'
    },
    {
      name: 'softData',
      documentation: 'The object currently under consideration.',
      factory: function() {
        var found = false;
        this.dao.find(this.data, {
          put: function(x) {
            found = true;
            this.softData = x;
          }.bind(this)
        });
        // Synchronous DAOs will already have called put, and I don't want to
        // overwrite the value.
        return found ? this.softData : '';
      },
      postSet: function(old, nu) {
        if (nu) {
          this.q = this.objectToQuery(nu);
          this.selected = true;
        }
      }
    },
    {
      name: 'q',
      label: 'Search',
      view: {
        factory_: 'foam.ui.md.TextFieldView',
        onKeyMode: true,
        floatingLabel: false
      },
      postSet: function(old, nu) {
        this.selected = false;
      }
    },
    {
      name: 'selected'
    },
    {
      name: 'subType',
      documentation: 'Based on ReferenceProperty, the name of the type.'
    },
    {
      name: 'subKey',
      documentation: 'The mLang expression for looking up the key from a ' +
          'whole object. Defaults to .ID',
      factory: function() {
        return FOAM.lookup(this.subType, this.X).ID;
      }
    },
    {
      model_: 'DAOProperty',
      name: 'dao',
      documentation: 'The DAO used to look up the models. Defaults to ' +
          'mySubTypeDAO for subType == "MySubType".',
      factory: function() {
        var name = this.subType[0].toLowerCase() + this.subType.substring(1);
        var daoName = name + 'DAO';
        return this.X[daoName];
      }
    },
    {
      name: 'wrappedDAO',
      factory: function() {
        return this.hideListOnSingle ?
            this.SingleEntryHidingDAO.create({ delegate: this.dao }) : this.dao;
      }
    },
    {
      model_: 'DAOProperty',
      name: 'filteredDAO',
      dynamicValue: function() {
        this.q; this.wrappedDAO; this.limit;
        var q = this.q ? this.queryFactory(this.q) : TRUE;
        var dao = this.wrappedDAO.where(q).limit(this.limit);
        return dao;
      },
      view: {
        factory_: 'DAOListView',
        className: 'rows',
        tagName: 'div',
        useSelection: true
      }
    },
    {
      name: 'queryFactory',
      defaultValue: function(q) { return STARTS_WITH_IC(this.subKey, q); }
    },
    {
      name: 'objectToQuery',
      documentation: 'Turns an object from the DAO into a query string.',
      factory: function() {
        return function(obj) { return this.subKey.f(obj); }.bind(this);
      }
    },
    {
      // TODO: DAO should be pre-limited instead
      name: 'limit',
      defaultValue: 40
    },
    {
      name: 'className',
      defaultValue: 'AddRowView'
    },
    {
      name: 'bodyId',
      factory: function() { return this.nextID(); }
    },
    {
      name: 'scrollerID',
      factory: function() { return this.nextID(); }
    },
    {
      name: 'hideListOnSingle',
      documentation: 'When true (the default), the suggestion list disappears when there is only one match. When false it is always visible.',
      defaultValue: true
    },
    {
      name: 'returnOnSelect',
      documentation: 'When true, updates $$DOC{ref:".data"} and returns when ' +
          'the user chooses an entry. When false, the query is updated to ' +
          'match the selected row.',
      defaultValue: true
    },
    {
      name: 'selection',
      postSet: function(old, nu) {
        if (nu) {
          if (this.returnOnSelect) {
            this.data = this.subKey.f(nu);
            this.doClose();
          } else {
            this.softData = nu;
          }
        }
      }
    }
  ],

  templates: [
    function CSS() {/*
      .AddRowView {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
        background: #fff;
        overflow: hidden;
      }
      .AddRowView .arvBody {
        flex-grow: 1;
        overflow-y: auto;
      }
      .AddRowView .rows {
        width: 100%;
        border: none;
      }
      .AddRowView .rows-row {
        padding: 0 12px 0 16px;
      }
    */},
    function toInnerHTML() {/*

        $$cancel $$accept
        $$q{ extraClassName: 'grow', clearAction: true }

        $$filteredDAO{ rowView: this.rowView }

    */}
  ],

  methods: {
    doClose: function() {
      // Don't close twice.
      if ( this.closed_ ) return;
      this.closed_ = true;

      this.stack.back();
    }
  },

  actions: [
    {
      name: 'cancel',
      label: '',
      iconUrl: 'images/ic_clear_24dp.png',
      isAvailable: function() { return !this.selected; },
      action: function() {
        this.doClose();
      }
    },
    {
      name: 'accept',
      label: '',
      iconUrl: 'images/ic_done_24dp.png',
      keyboardShortcuts: [ 13 /* enter */ ],
      isAvailable: function() { return this.selected; },
      action: function() {
        var key = this.subKey.f(this.softData);
        this.data = key;
        this.doClose();
      }
    }
  ]
});
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * a button for controlling whether sound is enabled or disabled for the sim and that is designed to work on the PhET
 * navigation bar
 *
 * @author John Blanco
 * @author Chris Klusendorf
 */

define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var joist = require( 'JOIST/joist' );
  var JoistA11yStrings = require( 'JOIST/JoistA11yStrings' );
  var JoistButton = require( 'JOIST/JoistButton' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );
  var ToggleNode = require( 'SUN/ToggleNode' );
  var Vector2 = require( 'DOT/Vector2' );

  // a11y strings
  var soundOnOffString = JoistA11yStrings.soundOnOffButton.value;

  // constants for node background
  var NODE_HEIGHT = 22.0;
  var NODE_WIDTH = NODE_HEIGHT * 1.13;

  // constants for drawing speaker
  var SPEAKER_HEIGHT = NODE_HEIGHT * 0.77;
  var SPEAKER_WIDTH = SPEAKER_HEIGHT * 0.58;
  var SPEAKER_BACK_WIDTH = SPEAKER_WIDTH * 0.46;
  var SPEAKER_BACK_HEIGHT = SPEAKER_HEIGHT * 0.35;
  var SPEAKER_BACK_Y_SPACE = ( SPEAKER_HEIGHT - SPEAKER_BACK_HEIGHT ) / 2.0; // space between top of speaker back and top of cone

  // constant for drawing sound off X
  var X_WIDTH = SPEAKER_HEIGHT * 0.52;

  // constants for drawing sound on curves
  var MAX_CURVE_RADIUS = SPEAKER_HEIGHT * 0.63;
  var RADIUS_STEPPER = SPEAKER_HEIGHT * 0.23;
  var MED_CURVE_RADIUS = MAX_CURVE_RADIUS - RADIUS_STEPPER;
  var MIN_CURVE_RADIUS = MED_CURVE_RADIUS - RADIUS_STEPPER;
  var CURVE_ANGLE = Math.PI / 2.7;
  var NEG_CURVE_ANGLE = CURVE_ANGLE * -1.0;

  /**
   * @param {BooleanProperty} soundEnabledProperty
   * @param {LookAndFeel} simLookAndFeel
   * @param {Tandem} tandem
   * @param {Object} [options]
   * @constructor
   */
  function NavigationBarSoundToggleButton( soundEnabledProperty, simLookAndFeel, tandem, options ) {

    options = _.extend( {
      highlightExtensionWidth: 5,
      highlightExtensionHeight: 10,
      highlightCenterOffsetY: 3,
      listener: function() {
        soundEnabledProperty.set( !soundEnabledProperty.get() );
      },

      // a11y
      tagName: 'button',
      innerContent: soundOnOffString
    }, options );

    var soundOnNode = new Node();
    var soundOffNode = new Node();
    var backgroundNode = new Rectangle( 0, 0, NODE_WIDTH, NODE_HEIGHT, { fill: 'transparent' } );
    soundOnNode.addChild( backgroundNode );
    soundOffNode.addChild( backgroundNode );

    // create speaker for both sound on and sound off
    var speakerNode = new Path(
      new Shape()
        .moveTo( SPEAKER_WIDTH, 0 )
        .lineTo( SPEAKER_BACK_WIDTH, SPEAKER_BACK_Y_SPACE )
        .lineTo( 0, SPEAKER_BACK_Y_SPACE )
        .lineToRelative( 0, SPEAKER_BACK_HEIGHT )
        .lineToRelative( SPEAKER_BACK_WIDTH, 0 )
        .lineTo( SPEAKER_WIDTH, SPEAKER_HEIGHT )
        .lineTo( SPEAKER_WIDTH, 0 )
        .close(),
      {
        stroke: 'black',
        lineWidth: 1.5,
        lineJoin: 'round',
        fill: 'black',
        centerY: soundOffNode.centerY,
        left: 0
      }
    );

    soundOnNode.addChild( speakerNode );
    soundOffNode.addChild( speakerNode );

    // create X for sound off
    var soundOffX = new Path(
      new Shape().moveTo( 0, 0 ).lineTo( X_WIDTH, X_WIDTH ).moveTo( 0, X_WIDTH ).lineTo( X_WIDTH, 0 ),
      {
        stroke: 'black',
        lineWidth: 1.7,
        lineCap: 'round',
        right: soundOffNode.width,
        centerY: soundOffNode.centerY
      }
    );
    soundOffNode.addChild( soundOffX );

    // create curved lines for sound on
    var soundOnCurves = new Path(
      new Shape()
        .arc( 0, 0, MAX_CURVE_RADIUS, CURVE_ANGLE, NEG_CURVE_ANGLE, true )
        .moveToPoint( new Vector2( MED_CURVE_RADIUS, 0 ).rotated( CURVE_ANGLE ) )
        .arc( 0, 0, MED_CURVE_RADIUS, CURVE_ANGLE, NEG_CURVE_ANGLE, true )
        .moveToPoint( new Vector2( MIN_CURVE_RADIUS, 0 ).rotated( CURVE_ANGLE ) )
        .arc( 0, 0, MIN_CURVE_RADIUS, CURVE_ANGLE, NEG_CURVE_ANGLE, true ),
      {
        stroke: 'black',
        lineWidth: 1.7,
        lineCap: 'round',
        right: soundOnNode.width,
        centerY: soundOnNode.centerY
      }
    );
    soundOnNode.addChild( soundOnCurves );

    var toggleNode = new ToggleNode(
      [
        { value: true, node: soundOnNode },
        { value: false, node: soundOffNode }
      ],
      soundEnabledProperty,
      { maxHeight: NODE_HEIGHT }
    );

    JoistButton.call( this, toggleNode, simLookAndFeel.navigationBarFillProperty, tandem, options );

    // change the icon so that it is visible when the navigation bar changes from dark to light
    simLookAndFeel.navigationBarDarkProperty.link( function( navigationBarDark ) {
      var baseColor = navigationBarDark ? 'black' : 'white';
      speakerNode.stroke = baseColor;
      speakerNode.fill = baseColor;
      soundOffX.stroke = baseColor;
      soundOnCurves.stroke = baseColor;
    } );
  }

  joist.register( 'NavigationBarSoundToggleButton', NavigationBarSoundToggleButton );

  return inherit( JoistButton, NavigationBarSoundToggleButton );

} );<commit_msg>Vertically center-aligned sounds icon with 'P', see https://github.com/phetsims/tambo/issues/19<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * a button for controlling whether sound is enabled or disabled for the sim and that is designed to work on the PhET
 * navigation bar
 *
 * @author John Blanco
 * @author Chris Klusendorf
 */

define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var joist = require( 'JOIST/joist' );
  var JoistA11yStrings = require( 'JOIST/JoistA11yStrings' );
  var JoistButton = require( 'JOIST/JoistButton' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );
  var ToggleNode = require( 'SUN/ToggleNode' );
  var Vector2 = require( 'DOT/Vector2' );

  // a11y strings
  var soundOnOffString = JoistA11yStrings.soundOnOffButton.value;

  // constants for node background
  var NODE_HEIGHT = 22.0;
  var NODE_WIDTH = NODE_HEIGHT * 1.13;

  // constants for drawing speaker
  var SPEAKER_HEIGHT = NODE_HEIGHT * 0.77;
  var SPEAKER_WIDTH = SPEAKER_HEIGHT * 0.58;
  var SPEAKER_BACK_WIDTH = SPEAKER_WIDTH * 0.46;
  var SPEAKER_BACK_HEIGHT = SPEAKER_HEIGHT * 0.35;
  var SPEAKER_BACK_Y_SPACE = ( SPEAKER_HEIGHT - SPEAKER_BACK_HEIGHT ) / 2.0; // space between top of speaker back and top of cone

  // constant for drawing sound off X
  var X_WIDTH = SPEAKER_HEIGHT * 0.52;

  // constants for drawing sound on curves
  var MAX_CURVE_RADIUS = SPEAKER_HEIGHT * 0.63;
  var RADIUS_STEPPER = SPEAKER_HEIGHT * 0.23;
  var MED_CURVE_RADIUS = MAX_CURVE_RADIUS - RADIUS_STEPPER;
  var MIN_CURVE_RADIUS = MED_CURVE_RADIUS - RADIUS_STEPPER;
  var CURVE_ANGLE = Math.PI / 2.7;
  var NEG_CURVE_ANGLE = CURVE_ANGLE * -1.0;

  /**
   * @param {BooleanProperty} soundEnabledProperty
   * @param {LookAndFeel} simLookAndFeel
   * @param {Tandem} tandem
   * @param {Object} [options]
   * @constructor
   */
  function NavigationBarSoundToggleButton( soundEnabledProperty, simLookAndFeel, tandem, options ) {

    options = _.extend( {
      highlightExtensionWidth: 5,
      highlightExtensionHeight: 10,
      highlightCenterOffsetY: 0,
      listener: function() {
        soundEnabledProperty.set( !soundEnabledProperty.get() );
      },

      // a11y
      tagName: 'button',
      innerContent: soundOnOffString
    }, options );

    var soundOnNode = new Node();
    var soundOffNode = new Node();
    var backgroundNode = new Rectangle( 0, 0, NODE_WIDTH, NODE_HEIGHT, { fill: 'transparent' } );
    soundOnNode.addChild( backgroundNode );
    soundOffNode.addChild( backgroundNode );

    // create speaker for both sound on and sound off
    var speakerNode = new Path(
      new Shape()
        .moveTo( SPEAKER_WIDTH, 0 )
        .lineTo( SPEAKER_BACK_WIDTH, SPEAKER_BACK_Y_SPACE )
        .lineTo( 0, SPEAKER_BACK_Y_SPACE )
        .lineToRelative( 0, SPEAKER_BACK_HEIGHT )
        .lineToRelative( SPEAKER_BACK_WIDTH, 0 )
        .lineTo( SPEAKER_WIDTH, SPEAKER_HEIGHT )
        .lineTo( SPEAKER_WIDTH, 0 )
        .close(),
      {
        stroke: 'black',
        lineWidth: 1.5,
        lineJoin: 'round',
        fill: 'black',
        centerY: soundOffNode.centerY,
        left: 0
      }
    );

    soundOnNode.addChild( speakerNode );
    soundOffNode.addChild( speakerNode );

    // create X for sound off
    var soundOffX = new Path(
      new Shape().moveTo( 0, 0 ).lineTo( X_WIDTH, X_WIDTH ).moveTo( 0, X_WIDTH ).lineTo( X_WIDTH, 0 ),
      {
        stroke: 'black',
        lineWidth: 1.7,
        lineCap: 'round',
        right: soundOffNode.width,
        centerY: soundOffNode.centerY
      }
    );
    soundOffNode.addChild( soundOffX );

    // create curved lines for sound on
    var soundOnCurves = new Path(
      new Shape()
        .arc( 0, 0, MAX_CURVE_RADIUS, CURVE_ANGLE, NEG_CURVE_ANGLE, true )
        .moveToPoint( new Vector2( MED_CURVE_RADIUS, 0 ).rotated( CURVE_ANGLE ) )
        .arc( 0, 0, MED_CURVE_RADIUS, CURVE_ANGLE, NEG_CURVE_ANGLE, true )
        .moveToPoint( new Vector2( MIN_CURVE_RADIUS, 0 ).rotated( CURVE_ANGLE ) )
        .arc( 0, 0, MIN_CURVE_RADIUS, CURVE_ANGLE, NEG_CURVE_ANGLE, true ),
      {
        stroke: 'black',
        lineWidth: 1.7,
        lineCap: 'round',
        right: soundOnNode.width,
        centerY: soundOnNode.centerY
      }
    );
    soundOnNode.addChild( soundOnCurves );

    var toggleNode = new ToggleNode(
      [
        { value: true, node: soundOnNode },
        { value: false, node: soundOffNode }
      ],
      soundEnabledProperty,
      { maxHeight: NODE_HEIGHT }
    );

    JoistButton.call( this, toggleNode, simLookAndFeel.navigationBarFillProperty, tandem, options );

    // change the icon so that it is visible when the navigation bar changes from dark to light
    simLookAndFeel.navigationBarDarkProperty.link( function( navigationBarDark ) {
      var baseColor = navigationBarDark ? 'black' : 'white';
      speakerNode.stroke = baseColor;
      speakerNode.fill = baseColor;
      soundOffX.stroke = baseColor;
      soundOnCurves.stroke = baseColor;
    } );
  }

  joist.register( 'NavigationBarSoundToggleButton', NavigationBarSoundToggleButton );

  return inherit( JoistButton, NavigationBarSoundToggleButton );

} );<|endoftext|>


<commit_before>;(function () {
    // bootstrap modal 封装
    function createModal(size, title, href) {
    	var template;
    	var $this = $(this);
        size = (size != undefined ? size : '');
        template = [
                        '
',
                        '
',
                        '
',
                        '
',
                        '
',
                        '
'
                    ].join("");
        var titleFlag = (title != undefined && title.trim() != ''),
            $modal = $(template),
            $modalContent = $modal.find('.modal-content')

        if (titleFlag) {
            $modalContent.html(
                ['
',
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>',
                '
', title, '
', // modal title
                '
'].join('')
            )
        }

        $.get(href, function(data) { // get modal content from server

            if (titleFlag) {
                $(data).insertAfter($modal.find('.modal-header'))
            } else {
                $modalContent.html(data)
            }

            // show modal
            $modal.modal()

            // Actually I mean to on show.bs.modal event
            // but it doesn't trigger
            $modal.on('shown.bs.modal', function () {
                $this.trigger('shown.fr.modal', $modal) // btn trigger shown.fr.modal event
            })
        })

        $modal.on('hidden.bs.modal', function () { // when the modal close remove it
            $modal.remove()
        })
    }

    // modal api
    $('body').on('click', 'a[data-toggle="front-modal"]', function (e) {
        e.preventDefault();
        createModal.call(this, $(this).data('size'), $(this).data('title'), $(this).data('href'));
    });

    // jquery common
    $.frontModal = function (option) {
        var preSetParams = {
            size: '',
            title: '',
            href: ''
        };

        var params = $.extend(preSetParams, option);

        createModal(params.size, params.title, params.href);
    };

    // 选择浮层
    // when [data-toggle="front-modal"] show then we can catch the shown.fr.modal event
    // to do some bind operation
    $('[data-toggle="front-modal-select"]')
        .on('click', createModal)
        .on('shown.fr.modal', selectModalInit)

    function selectModalInit() {
        var $this = $(this),
            $selectedArea = $('#front-selected-item')

        // search btn
        $('#front-search-btn').click(function() {
            $this.trigger('search.fr.modal.select')
        })

        // search input enter
        $('#front-search-input').keyup(function () {
            if (window.event.keyCode == 13) {
                $('#front-search-btn').click()
            }
        })

        // add up operation
        $('#front-tab-content').on('click', '.front-select-item>span', function (e) {
            var $span = $(e.target),
                $selectedItem = $selectedArea.children('.front-select-item'),
                i = 0,
                exist = false;

            for (;!exist && i < $selectedItem.length; ++i) {
                if ($selectedItem.eq(i).children('span').text() === $span.text()) {
                    exist = true;
                }
            }

            if (!exist) {
                $selectedArea.append([
                    '
',
                    '', $span.text(), '',
                    '删除',
                    '
'
                ].join(""))

                calSelectedNumber()
            }
        })

        // delete event on
        $selectedArea.on('click', 'a[data-toggle="delete"]', function(e) {
            var $this = $(this)
            e.preventDefault()
            $this.parent().remove()

            calSelectedNumber()
        })

        // clear selected item
        $('#fr-clear-item').click(function() {
            $selectedArea.html('')
            calSelectedNumber()

            return false
        })

        // update selected number
        function calSelectedNumber() {
            $('#front-item-num>span').text($selectedArea.children('.front-select-item').length)
        }
    }
})();
<commit_msg>ADD：return $modal to support link operation<commit_after>;(function () {
    // bootstrap modal 封装
    function createModal(size, title, href) {
    	var template;
    	var $this = $(this);
        size = (size != undefined ? size : '');
        template = [
                        '
',
                        '
',
                        '
',
                        '
',
                        '
',
                        '
'
                    ].join("");
        var titleFlag = (title != undefined && title.trim() != ''),
            $modal = $(template),
            $modalContent = $modal.find('.modal-content')

        if (titleFlag) {
            $modalContent.html(
                ['
',
                '<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>',
                '
', title, '
', // modal title
                '
'].join('')
            )
        }

        $.get(href, function(data) { // get modal content from server

            if (titleFlag) {
                $(data).insertAfter($modal.find('.modal-header'))
            } else {
                $modalContent.html(data)
            }

            // show modal
            $modal.modal()

            // Actually I mean to on show.bs.modal event
            // but it doesn't trigger
            $modal.on('shown.bs.modal', function () {
                $this.trigger('shown.fr.modal', $modal) // btn trigger shown.fr.modal event
            })
        })

        $modal.on('hidden.bs.modal', function () { // when the modal close remove it
            $modal.remove()
        })

        return $modal;
    }

    // modal api
    $('body').on('click', 'a[data-toggle="front-modal"]', function (e) {
        e.preventDefault();
        createModal.call(this, $(this).data('size'), $(this).data('title'), $(this).data('href'));
    });

    // jquery common
    $.frontModal = function (option) {
        var preSetParams = {
            size: '',
            title: '',
            href: ''
        };

        var params = $.extend(preSetParams, option);

        return createModal(params.size, params.title, params.href);
    };

    // 选择浮层
    // when [data-toggle="front-modal"] show then we can catch the shown.fr.modal event
    // to do some bind operation
    $('[data-toggle="front-modal-select"]')
        .on('click', createModal)
        .on('shown.fr.modal', selectModalInit)

    function selectModalInit() {
        var $this = $(this),
            $selectedArea = $('#front-selected-item')

        // search btn
        $('#front-search-btn').click(function() {
            $this.trigger('search.fr.modal.select')
        })

        // search input enter
        $('#front-search-input').keyup(function () {
            if (window.event.keyCode == 13) {
                $('#front-search-btn').click()
            }
        })

        // add up operation
        $('#front-tab-content').on('click', '.front-select-item>span', function (e) {
            var $span = $(e.target),
                $selectedItem = $selectedArea.children('.front-select-item'),
                i = 0,
                exist = false;

            for (;!exist && i < $selectedItem.length; ++i) {
                if ($selectedItem.eq(i).children('span').text() === $span.text()) {
                    exist = true;
                }
            }

            if (!exist) {
                $selectedArea.append([
                    '
',
                    '', $span.text(), '',
                    '删除',
                    '
'
                ].join(""))

                calSelectedNumber()
            }
        })

        // delete event on
        $selectedArea.on('click', 'a[data-toggle="delete"]', function(e) {
            var $this = $(this)
            e.preventDefault()
            $this.parent().remove()

            calSelectedNumber()
        })

        // clear selected item
        $('#fr-clear-item').click(function() {
            $selectedArea.html('')
            calSelectedNumber()

            return false
        })

        // update selected number
        function calSelectedNumber() {
            $('#front-item-num>span').text($selectedArea.children('.front-select-item').length)
        }
    }
})();
<|endoftext|>


<commit_before>iD.behavior.DragNode = function(context) {
    var nudgeInterval;

    function edge(point, size) {
        var pad = [30, 100, 30, 100];
        if (point[0] > size[0] - pad[0]) return [-10, 0];
        else if (point[0] < pad[2]) return [10, 0];
        else if (point[1] > size[1] - pad[1]) return [0, -10];
        else if (point[1] < pad[3]) return [0, 10];
        return null;
    }

    function startNudge(nudge) {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = window.setInterval(function() {
            context.map().pan(nudge).redraw();
        }, 50);
    }

    function stopNudge() {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = null;
    }

    function moveAnnotation(entity) {
        return t('operations.move.annotation.' + entity.geometry(context.graph()));
    }

    function connectAnnotation(datum) {
        return t('operations.connect.annotation.' + datum.geometry(context.graph()));
    }

    function origin(entity) {
        return context.projection(entity.loc);
    }

    function start(entity) {
        var activeIDs = _.pluck(context.graph().parentWays(entity), 'id');
        activeIDs.push(entity.id);

        context.surface()
            .classed('behavior-drag-node', true)
            .selectAll('.node, .way')
            .filter(function (d) { return activeIDs.indexOf(d.id) >= 0; })
            .classed('active', true);

        context.perform(
            iD.actions.Noop());
    }

    function datum() {
        if (d3.event.sourceEvent.altKey) {
            return {};
        } else {
            return d3.event.sourceEvent.target.__data__ || {};
        }
    }

    function move(entity) {
        d3.event.sourceEvent.stopPropagation();

        var nudge = edge(d3.event.point, context.map().size());
        if (nudge) startNudge(nudge);
        else stopNudge();

        var loc = context.map().mouseCoordinates();

        var d = datum();
        if (d.type === 'node') {
            loc = d.loc;
        } else if (d.type === 'way') {
            loc = iD.geo.chooseIndex(d, d3.mouse(context.surface().node()), context).loc;
        }

        context.replace(iD.actions.MoveNode(entity.id, loc));
    }

    function end(entity) {
        context.surface()
            .classed('behavior-drag-node', false)
            .selectAll('.active')
            .classed('active', false);

        stopNudge();

        var d = datum();
        if (d.type === 'way') {
            var choice = iD.geo.chooseIndex(d, d3.mouse(context.surface().node()), context);
            context.replace(
                iD.actions.MoveNode(entity.id, choice.loc),
                iD.actions.AddVertex(d.id, entity.id, choice.index),
                connectAnnotation(d));

        } else if (d.type === 'node' && d.id !== entity.id) {
            context.replace(
                iD.actions.Connect([entity.id, d.id]),
                connectAnnotation(d));

        } else {
            context.replace(
                iD.actions.Noop(),
                moveAnnotation(entity));
        }
    }

    return iD.behavior.drag()
        .delegate("g.node")
        .origin(origin)
        .on('start', start)
        .on('move', move)
        .on('end', end);
};
<commit_msg>Fix point dragging<commit_after>iD.behavior.DragNode = function(context) {
    var nudgeInterval;

    function edge(point, size) {
        var pad = [30, 100, 30, 100];
        if (point[0] > size[0] - pad[0]) return [-10, 0];
        else if (point[0] < pad[2]) return [10, 0];
        else if (point[1] > size[1] - pad[1]) return [0, -10];
        else if (point[1] < pad[3]) return [0, 10];
        return null;
    }

    function startNudge(nudge) {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = window.setInterval(function() {
            context.map().pan(nudge).redraw();
        }, 50);
    }

    function stopNudge() {
        if (nudgeInterval) window.clearInterval(nudgeInterval);
        nudgeInterval = null;
    }

    function moveAnnotation(entity) {
        return t('operations.move.annotation.' + entity.geometry(context.graph()));
    }

    function connectAnnotation(datum) {
        return t('operations.connect.annotation.' + datum.geometry(context.graph()));
    }

    function origin(entity) {
        return context.projection(entity.loc);
    }

    function start(entity) {
        var activeIDs = _.pluck(context.graph().parentWays(entity), 'id');
        activeIDs.push(entity.id);

        context.surface()
            .classed('behavior-drag-node', true)
            .selectAll('.node, .way')
            .filter(function (d) { return activeIDs.indexOf(d.id) >= 0; })
            .classed('active', true);

        context.perform(
            iD.actions.Noop());
    }

    function datum() {
        if (d3.event.sourceEvent.altKey) {
            return {};
        } else {
            return d3.event.sourceEvent.target.__data__ || {};
        }
    }

    function move(entity) {
        d3.event.sourceEvent.stopPropagation();

        var nudge = edge(d3.event.point, context.map().size());
        if (nudge) startNudge(nudge);
        else stopNudge();

        var loc = context.map().mouseCoordinates();

        var d = datum();
        if (d.type === 'node' && d.id !== entity.id) {
            loc = d.loc;
        } else if (d.type === 'way') {
            loc = iD.geo.chooseIndex(d, d3.mouse(context.surface().node()), context).loc;
        }

        context.replace(iD.actions.MoveNode(entity.id, loc));
    }

    function end(entity) {
        context.surface()
            .classed('behavior-drag-node', false)
            .selectAll('.active')
            .classed('active', false);

        stopNudge();

        var d = datum();
        if (d.type === 'way') {
            var choice = iD.geo.chooseIndex(d, d3.mouse(context.surface().node()), context);
            context.replace(
                iD.actions.MoveNode(entity.id, choice.loc),
                iD.actions.AddVertex(d.id, entity.id, choice.index),
                connectAnnotation(d));

        } else if (d.type === 'node' && d.id !== entity.id) {
            context.replace(
                iD.actions.Connect([entity.id, d.id]),
                connectAnnotation(d));

        } else {
            context.replace(
                iD.actions.Noop(),
                moveAnnotation(entity));
        }
    }

    return iD.behavior.drag()
        .delegate("g.node")
        .origin(origin)
        .on('start', start)
        .on('move', move)
        .on('end', end);
};
<|endoftext|>


<commit_before>/*
Possible additions:
	scollTop
	CSS Matrix
*/

$.extend( $.support, {
	orientation: "orientation" in window,
	touch: typeof Touch === "object",
	WebKitAnimationEvent: typeof WebKitTransitionEvent === "object",
	pushState: !!history.pushState
});

(function() {
	var fakeBody = $( "" ).prependTo( "html" ),
		displayDiv = $( "
" )
			.prependTo( fakeBody )[ 0 ],
		positionDiv = $( "
" +
				"

").prependTo( fakeBody )[ 0 ],
		floatClearHtml = "
",
		floatClearWrap = $( "
" )
			.append( floatClearHtml + floatClearHtml )
			.prependTo( fakeBody ),
		floatClearDivs = floatClearWrap.children(),
		floatClearDiv1Top = floatClearDivs[ 0 ].offsetTop,
		floatClearDiv2 = floatClearDivs[ 1 ],
		supportFloatClear = false;

	if ( floatClearDiv1Top === floatClearDiv2.offsetTop ) {
		floatClearDiv2.style.clear = "left";
		if ( floatClearDiv1Top !== floatClearDiv2.offsetTop ) {
			supportFloatClear = true;
		}
	}

	$.extend( $.support, {
		display: displayDiv.offsetHeight === 0,
		position: positionDiv.offsetLeft === 10,
		overflow: positionDiv.offsetHeight === 0,
		floatclear: supportFloatClear
	});

	fakeBody.remove();
})();

// test whether a CSS media type or query applies
$.media = (function() {
	// TODO: use window.matchMedia once at least one UA implements it
	var cache = {},
		testDiv = $( "
" ),
		fakeBody = $( "" ).append( testDiv );

	return function( query ) {
		if ( !( query in cache ) ) {
			var styleBlock = $( "" );
			$html.prepend( fakeBody ).prepend( styleBlock );
			cache[ query ] = testDiv.css( "position" ) === "absolute";
			fakeBody.add( styleBlock ).remove();
		}
		return cache[ query ];
	};
})();
<commit_msg>Fixed bad variable reference.<commit_after>/*
Possible additions:
	scollTop
	CSS Matrix
*/

$.extend( $.support, {
	orientation: "orientation" in window,
	touch: typeof Touch === "object",
	WebKitAnimationEvent: typeof WebKitTransitionEvent === "object",
	pushState: !!history.pushState
});

(function() {
	var fakeBody = $( "" ).prependTo( "html" ),
		displayDiv = $( "
" )
			.prependTo( fakeBody )[ 0 ],
		positionDiv = $( "
" +
				"

").prependTo( fakeBody )[ 0 ],
		floatClearHtml = "
",
		floatClearWrap = $( "
" )
			.append( floatClearHtml + floatClearHtml )
			.prependTo( fakeBody ),
		floatClearDivs = floatClearWrap.children(),
		floatClearDiv1Top = floatClearDivs[ 0 ].offsetTop,
		floatClearDiv2 = floatClearDivs[ 1 ],
		supportFloatClear = false;

	if ( floatClearDiv1Top === floatClearDiv2.offsetTop ) {
		floatClearDiv2.style.clear = "left";
		if ( floatClearDiv1Top !== floatClearDiv2.offsetTop ) {
			supportFloatClear = true;
		}
	}

	$.extend( $.support, {
		display: displayDiv.offsetHeight === 0,
		position: positionDiv.offsetLeft === 10,
		overflow: positionDiv.offsetHeight === 0,
		floatclear: supportFloatClear
	});

	fakeBody.remove();
})();

// test whether a CSS media type or query applies
$.media = (function() {
	// TODO: use window.matchMedia once at least one UA implements it
	var cache = {},
		$html = $( "html" ),
		testDiv = $( "
" ),
		fakeBody = $( "" ).append( testDiv );

	return function( query ) {
		if ( !( query in cache ) ) {
			var styleBlock = $( "" );
			$html.prepend( fakeBody ).prepend( styleBlock );
			cache[ query ] = testDiv.css( "position" ) === "absolute";
			fakeBody.add( styleBlock ).remove();
		}
		return cache[ query ];
	};
})();
<|endoftext|>


<commit_before>(function( $ ) {

  $.fn.onthegithubs = function( options ) {

    var settings = $.extend({
      // event-source: "repos/kvz/nsfailover",
    }, options || {});
    var self = this;

    var makeHtmlUrl = function (url) {
      var result = url;

      result = result.replace(/\/users\//, '/');
      result = result.replace(/\/repos\//, '/');
      result = result.replace(/\/api\./, '/');
      result = result.replace(/\/commits\//, '/commit/');

      return result;
    };

    var templater = function (template, vars) {
      return template.replace(/\{([^\}]*)\}/g, function(m, key) {
        return vars.hasOwnProperty(key) ? vars[key] : "";
      });
    };

    var download = function (source) {
      if (!source) {
        throw Error('Please set an event source like "orgs/tus" via data-event-source attr or options');
      }

      var d       = $.Deferred();
      var githubs = localStorage.getItem('on-the-githubs-feed-' + source);
      var time    = localStorage.getItem('on-the-githubs-date-' + source);
      var now     = +new Date() / 1000;
      var url     = 'https://api.github.com/' + source + '/events?per_page=20&callback=?';

      githubs = JSON.parse(githubs);
      if (githubs && githubs.data && time && now - time < 3 * 60) {
        d.resolve(githubs);
        return d;
      }

      $.getJSON(url, function(data, textStatus, jqXHR) {
        if (data.data.message) {
          throw Error('GitHub says: ' + data.data.message + ' for url: ' + url);
        }
        data.data = data.data.slice(0, 20);

        localStorage.setItem('on-the-githubs-feed-' + source, JSON.stringify(data));
        localStorage.setItem('on-the-githubs-date-' + source, now);
        d.resolve(data);
      });

      return d;
    };

    return this.each(function() {
      var $obj  = $(this);
      var eventSource;
      var val;
      if ((val = settings['event-source'])) {
        eventSource = val;
      } else if ((val = $obj.data('event-source'))) {
        eventSource = val;
      }

      download(eventSource).done(function (data) {
        $obj.html('');

        var template = '{created}';
        template    += '';
        template    += '
{username} ';
        template    += '{action}';
        template    += ' {repoName}{branch}{commits}
';
        template    += '

';

        for (var i = 0; i < data.data.length; i++) {
          var item = data.data[i];

          var gravatarSrc = item.actor.avatar_url + '&s=64';
          var username    = item.actor.login;
          var action      = '';
          var branch      = '';
          var commits     = '';

          // http://developer.github.com/v3/activity/events/types/
          var isClosed = false;

          switch (item.type) {
            case 'IssuesEvent':
              // console.log(item);
              isClosed = item.payload.issue.state === 'closed';
              action   = item.payload.action + ' ';
              action  += 'issue ';

              if (isClosed) {
                action += '<s>';
              }
              action += item.payload.issue.title;
              if (isClosed) {
                action += '</s>';
              }

              action += ' on';
              break;
            case 'CommitCommentEvent':
              action  = 'commented "' + item.payload.comment.body + '" ';
              action += 'on a commit to ';
              action += item.payload.comment.path + ' in';
              break;
            case 'IssueCommentEvent':
              isClosed = item.payload.issue.state === 'closed';

              action  = 'commented on ';
              if (isClosed) {
                action += '<s>';
              }
              action += item.payload.issue.title;
              if (isClosed) {
                action += '</s>';
              }
              action += ' in';
              break;
            case 'PushEvent':
              // var commitString = item.payload.commits.length === 1 ? 'commit' : 'commits';

              if (!item.payload || !item.payload.commits || item.payload.commits.length === 0) {
                break;
              }
              var firstCommit = item.payload.commits[0].sha;
              var firstUrl    = makeHtmlUrl(item.payload.commits[0].url);
              var lastCommit  = '';
              var messages    = [];
              var msg         = '';
              for (var j in item.payload.commits) {
                lastCommit = item.payload.commits[j].sha;
                msg = item.payload.commits[j].message.substr(0, 50);
                if (msg.length > item.payload.commits[j].message.length) {
                  msg += ' ...';
                }
                messages.push(msg);
              }
              var compareUrl  = firstUrl.replace('commit', 'compare').replace(firstCommit, firstCommit + '...' + lastCommit);
              var txtMessages = messages.join(' — ');

              action  = 'pushed ';
              if (item.payload.commits.length === 1) {
                action += '';
                action += '1 commit';
                action += '';
              } else {
                action += '';
                action += item.payload.commits.length + ' ' + 'commits';
                action += '';
              }
              action += ' to';

              // commits = '
';
              // for (var j in item.payload.commits) {
              //   var commit = item.payload.commits[j];

              //   var sha = commit.sha.substr(0, 7);
              //   var msg = commit.message.substr(0, 50);
              //   if (msg.length !== commit.message.length) {
              //     msg += ' ...';
              //   }

              //   commits += '
';
              //   commits += '' + sha + '';
              //   commits += ' ' + msg;
              //   commits += '
';
              // }

              // commits += '
';
              // console.log(item.type, item);
              break;
            case 'ForkEvent':
              action = 'forked';
              break;
            case 'WatchEvent':
              action = 'is now watching';
              break;
            case 'PullRequestEvent':
              action  = item.payload.action + ' ';
              action += 'pull request ';
              action += item.payload.pull_request.title;
              action += ' for';

              break;
            case 'CreateEvent':
              action = 'created a new ' + item.payload.ref_type + ' in';
              branch = ': ' + item.payload.ref + '';
              break;
            default:
              console.log(item.type, item);
              break;
          }

          var entry = templater(template, {
            gravatarSrc: gravatarSrc,
            userUrl: makeHtmlUrl(item.actor.url),
            username: username,
            repoUrl: makeHtmlUrl(item.repo.url),
            repoName: item.repo.name,
            branch: branch,
            created: item.created_at,
            action: action,
            commits: commits
          });

          $('
').append(entry).appendTo($obj);
        }

        $('abbr.timeago').timeago();
        $('a[rel]').tooltip();
      });
    });
  };
}( jQuery ));
<commit_msg>Only call tooltip & timeago when they exist<commit_after>(function( $ ) {

  $.fn.onthegithubs = function( options ) {

    var settings = $.extend({
      // event-source: "repos/kvz/nsfailover",
    }, options || {});
    var self = this;

    var makeHtmlUrl = function (url) {
      var result = url;

      result = result.replace(/\/users\//, '/');
      result = result.replace(/\/repos\//, '/');
      result = result.replace(/\/api\./, '/');
      result = result.replace(/\/commits\//, '/commit/');

      return result;
    };

    var templater = function (template, vars) {
      return template.replace(/\{([^\}]*)\}/g, function(m, key) {
        return vars.hasOwnProperty(key) ? vars[key] : "";
      });
    };

    var download = function (source) {
      if (!source) {
        throw Error('Please set an event source like "orgs/tus" via data-event-source attr or options');
      }

      var d       = $.Deferred();
      var githubs = localStorage.getItem('on-the-githubs-feed-' + source);
      var time    = localStorage.getItem('on-the-githubs-date-' + source);
      var now     = +new Date() / 1000;
      var url     = 'https://api.github.com/' + source + '/events?per_page=20&callback=?';

      githubs = JSON.parse(githubs);
      if (githubs && githubs.data && time && now - time < 3 * 60) {
        d.resolve(githubs);
        return d;
      }

      $.getJSON(url, function(data, textStatus, jqXHR) {
        if (data.data.message) {
          throw Error('GitHub says: ' + data.data.message + ' for url: ' + url);
        }
        data.data = data.data.slice(0, 20);

        localStorage.setItem('on-the-githubs-feed-' + source, JSON.stringify(data));
        localStorage.setItem('on-the-githubs-date-' + source, now);
        d.resolve(data);
      });

      return d;
    };

    return this.each(function() {
      var $obj  = $(this);
      var eventSource;
      var val;
      if ((val = settings['event-source'])) {
        eventSource = val;
      } else if ((val = $obj.data('event-source'))) {
        eventSource = val;
      }

      download(eventSource).done(function (data) {
        $obj.html('');

        var template = '{created}';
        template    += '';
        template    += '
{username} ';
        template    += '{action}';
        template    += ' {repoName}{branch}{commits}
';
        template    += '

';

        for (var i = 0; i < data.data.length; i++) {
          var item = data.data[i];

          var gravatarSrc = item.actor.avatar_url + '&s=64';
          var username    = item.actor.login;
          var action      = '';
          var branch      = '';
          var commits     = '';

          // http://developer.github.com/v3/activity/events/types/
          var isClosed = false;

          switch (item.type) {
            case 'IssuesEvent':
              // console.log(item);
              isClosed = item.payload.issue.state === 'closed';
              action   = item.payload.action + ' ';
              action  += 'issue ';

              if (isClosed) {
                action += '<s>';
              }
              action += item.payload.issue.title;
              if (isClosed) {
                action += '</s>';
              }

              action += ' on';
              break;
            case 'CommitCommentEvent':
              action  = 'commented "' + item.payload.comment.body + '" ';
              action += 'on a commit to ';
              action += item.payload.comment.path + ' in';
              break;
            case 'IssueCommentEvent':
              isClosed = item.payload.issue.state === 'closed';

              action  = 'commented on ';
              if (isClosed) {
                action += '<s>';
              }
              action += item.payload.issue.title;
              if (isClosed) {
                action += '</s>';
              }
              action += ' in';
              break;
            case 'PushEvent':
              // var commitString = item.payload.commits.length === 1 ? 'commit' : 'commits';

              if (!item.payload || !item.payload.commits || item.payload.commits.length === 0) {
                break;
              }
              var firstCommit = item.payload.commits[0].sha;
              var firstUrl    = makeHtmlUrl(item.payload.commits[0].url);
              var lastCommit  = '';
              var messages    = [];
              var msg         = '';
              for (var j in item.payload.commits) {
                lastCommit = item.payload.commits[j].sha;
                msg = item.payload.commits[j].message.substr(0, 50);
                if (msg.length > item.payload.commits[j].message.length) {
                  msg += ' ...';
                }
                messages.push(msg);
              }
              var compareUrl  = firstUrl.replace('commit', 'compare').replace(firstCommit, firstCommit + '...' + lastCommit);
              var txtMessages = messages.join(' — ');

              action  = 'pushed ';
              if (item.payload.commits.length === 1) {
                action += '';
                action += '1 commit';
                action += '';
              } else {
                action += '';
                action += item.payload.commits.length + ' ' + 'commits';
                action += '';
              }
              action += ' to';

              // commits = '
';
              // for (var j in item.payload.commits) {
              //   var commit = item.payload.commits[j];

              //   var sha = commit.sha.substr(0, 7);
              //   var msg = commit.message.substr(0, 50);
              //   if (msg.length !== commit.message.length) {
              //     msg += ' ...';
              //   }

              //   commits += '
';
              //   commits += '' + sha + '';
              //   commits += ' ' + msg;
              //   commits += '
';
              // }

              // commits += '
';
              // console.log(item.type, item);
              break;
            case 'ForkEvent':
              action = 'forked';
              break;
            case 'WatchEvent':
              action = 'is now watching';
              break;
            case 'PullRequestEvent':
              action  = item.payload.action + ' ';
              action += 'pull request ';
              action += item.payload.pull_request.title;
              action += ' for';

              break;
            case 'CreateEvent':
              action = 'created a new ' + item.payload.ref_type + ' in';
              branch = ': ' + item.payload.ref + '';
              break;
            default:
              console.log(item.type, item);
              break;
          }

          var entry = templater(template, {
            gravatarSrc: gravatarSrc,
            userUrl: makeHtmlUrl(item.actor.url),
            username: username,
            repoUrl: makeHtmlUrl(item.repo.url),
            repoName: item.repo.name,
            branch: branch,
            created: item.created_at,
            action: action,
            commits: commits
          });

          $('
').append(entry).appendTo($obj);
        }

        if ('timeago' in $('abbr.timeago')) {
          $('abbr.timeago').timeago();
        }
        if ('tooltip' in $('a[rel]')) {
          $('a[rel]').tooltip();
        }
      });
    });
  };
}( jQuery ));
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('foundation.panel', ['foundation.core'])
    .directive('zfPanel', zfPanel)
    .service('FoundationPanel', FoundationPanel)
  ;

  FoundationPanel.$inject = ['FoundationApi'];

  function FoundationPanel(foundationApi) {
    var service    = {};

    service.activate = activate;
    service.deactivate = deactivate;

    return service;

    //target should be element ID
    function activate(target) {
      foundationApi.publish(target, 'show');
    }

    //target should be element ID
    function deactivate(target) {
      foundationApi.publish(target, 'hide');
    }
  }

  zfPanel.$inject = ['FoundationApi', '$window'];

  function zfPanel(foundationApi, $window) {
    var directive = {
      restrict: 'EA',
      templateUrl: 'components/panel/panel.html',
      transclude: true,
      scope: {
        position: '@?'
      },
      replace: true,
      compile: compile
    };

    return directive;

    function compile(tElement, tAttrs, transclude) {
      var type = 'panel';

      return {
        pre: preLink,
        post: postLink
      };

      function preLink(scope, iElement, iAttrs, controller) {
        iAttrs.$set('zf-closable', type);
        scope.position = scope.position || 'left';
        scope.positionClass = 'panel-' + scope.position;
      }

      function postLink(scope, element, attrs) {
        scope.active = false;
        var animationIn, animationOut;
        var globalQueries = foundationApi.getSettings().mediaQueries;

        //urgh, there must be a better way
        if(scope.position === 'left') {
          animationIn  = attrs.animationIn || 'slideInRight';
          animationOut = attrs.animationOut || 'slideOutLeft';
        } else if (scope.position === 'right') {
          animationIn  = attrs.animationIn || 'slideInLeft';
          animationOut = attrs.animationOut || 'slideOutRight';
        } else if (scope.position === 'top') {
          animationIn  = attrs.animationIn || 'slideInDown';
          animationOut = attrs.animationOut || 'slideOutUp';
        } else if (scope.position === 'bottom') {
          animationIn  = attrs.animationIn || 'slideInUp';
          animationOut = attrs.animationOut || 'slideOutBottom';
        }

        //setup
        foundationApi.subscribe(attrs.id, function(msg) {
          var panelPosition = $window.getComputedStyle(element[0]).getPropertyValue("position");

          // patch to prevent panel animation on larger screen devices
          if (panelPosition !== 'absolute') {
            return;
          }

          if(msg == 'show' || msg == 'open') {
            scope.show();
          } else if (msg == 'close' || msg == 'hide') {
            scope.hide();
          } else if (msg == 'toggle') {
            scope.toggle();
          }

          if (!scope.$root.$$phase) {
            scope.$apply();
          }

          return;
        });

        scope.hide = function() {
          if(scope.active){
            scope.active = false;
            foundationApi.animate(element, scope.active, animationIn, animationOut);
          }

          return;
        };

        scope.show = function() {
          if(!scope.active){
            scope.active = true;
            foundationApi.animate(element, scope.active, animationIn, animationOut);
          }

          return;
        };

        scope.toggle = function() {
          scope.active = !scope.active;
          foundationApi.animate(element, scope.active, animationIn, animationOut);

          return;
        };

        element.on('click', function(e) {
          //check sizing
          var srcEl = e.srcElement;

          if(!matchMedia(globalQueries.medium).matches && srcEl.href && srcEl.href.length > 0) {
            //hide element if it can't match at least medium
            scope.hide();
            foundationApi.animate(element, scope.active, animationIn, animationOut);
          }
        });
      }
    }
  }

})();
<commit_msg>Use event.target instead of event.srcElement for panel closing, fixes #548<commit_after>(function() {
  'use strict';

  angular.module('foundation.panel', ['foundation.core'])
    .directive('zfPanel', zfPanel)
    .service('FoundationPanel', FoundationPanel)
  ;

  FoundationPanel.$inject = ['FoundationApi'];

  function FoundationPanel(foundationApi) {
    var service    = {};

    service.activate = activate;
    service.deactivate = deactivate;

    return service;

    //target should be element ID
    function activate(target) {
      foundationApi.publish(target, 'show');
    }

    //target should be element ID
    function deactivate(target) {
      foundationApi.publish(target, 'hide');
    }
  }

  zfPanel.$inject = ['FoundationApi', '$window'];

  function zfPanel(foundationApi, $window) {
    var directive = {
      restrict: 'EA',
      templateUrl: 'components/panel/panel.html',
      transclude: true,
      scope: {
        position: '@?'
      },
      replace: true,
      compile: compile
    };

    return directive;

    function compile(tElement, tAttrs, transclude) {
      var type = 'panel';

      return {
        pre: preLink,
        post: postLink
      };

      function preLink(scope, iElement, iAttrs, controller) {
        iAttrs.$set('zf-closable', type);
        scope.position = scope.position || 'left';
        scope.positionClass = 'panel-' + scope.position;
      }

      function postLink(scope, element, attrs) {
        scope.active = false;
        var animationIn, animationOut;
        var globalQueries = foundationApi.getSettings().mediaQueries;

        //urgh, there must be a better way
        if(scope.position === 'left') {
          animationIn  = attrs.animationIn || 'slideInRight';
          animationOut = attrs.animationOut || 'slideOutLeft';
        } else if (scope.position === 'right') {
          animationIn  = attrs.animationIn || 'slideInLeft';
          animationOut = attrs.animationOut || 'slideOutRight';
        } else if (scope.position === 'top') {
          animationIn  = attrs.animationIn || 'slideInDown';
          animationOut = attrs.animationOut || 'slideOutUp';
        } else if (scope.position === 'bottom') {
          animationIn  = attrs.animationIn || 'slideInUp';
          animationOut = attrs.animationOut || 'slideOutBottom';
        }

        //setup
        foundationApi.subscribe(attrs.id, function(msg) {
          var panelPosition = $window.getComputedStyle(element[0]).getPropertyValue("position");

          // patch to prevent panel animation on larger screen devices
          if (panelPosition !== 'absolute') {
            return;
          }

          if(msg == 'show' || msg == 'open') {
            scope.show();
          } else if (msg == 'close' || msg == 'hide') {
            scope.hide();
          } else if (msg == 'toggle') {
            scope.toggle();
          }

          if (!scope.$root.$$phase) {
            scope.$apply();
          }

          return;
        });

        scope.hide = function() {
          if(scope.active){
            scope.active = false;
            foundationApi.animate(element, scope.active, animationIn, animationOut);
          }

          return;
        };

        scope.show = function() {
          if(!scope.active){
            scope.active = true;
            foundationApi.animate(element, scope.active, animationIn, animationOut);
          }

          return;
        };

        scope.toggle = function() {
          scope.active = !scope.active;
          foundationApi.animate(element, scope.active, animationIn, animationOut);

          return;
        };

        element.on('click', function(e) {
          // Check sizing
          var srcEl = e.target;

          if (!matchMedia(globalQueries.medium).matches && srcEl.href && srcEl.href.length > 0) {
            // Hide element if it can't match at least medium
            scope.hide();
            foundationApi.animate(element, scope.active, animationIn, animationOut);
          }
        });
      }
    }
  }

})();
<|endoftext|>