<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormGroup, Modal, Radio } from 'react-bootstrap';
import RosterRacer from './Racer';
import RaceSetup from './RaceSetup';
import style from './roster.css';

const racerAttributeRadioGroup = (key, options, onChange) => (
  <FormGroup
    key={`${key}-option-group`}
    style={{
      float: 'left',
      display: 'inline-block',
      width: '50%',
      paddingLeft: '5px'
    }}
  >
    {key}
    {options.map(option => (
      <Radio
        key={`${option}-radio-btn`}
        name={key}
        value={option}
        onChange={onChange}
      >
        {option}
      </Radio>
    ))}
  </FormGroup>
);

export default class Roster extends Component {
  static propTypes = {
    bikes: PropTypes.array.isRequired,
    races: PropTypes.array.isRequired,
    addRaces: PropTypes.func.isRequired,
    racers: PropTypes.array.isRequired,
    racerAttributes: PropTypes.object.isRequired,
    addRacer: PropTypes.func.isRequired,
    removeRacers: PropTypes.func.isRequired,
    editRacer: PropTypes.func
  };

  constructor(props, context) {
    super(props, context);
    this.state = {
      search: '',
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      selectedRacers: [],
      showModal: false
    };
  }

  handleSearch(e) {
    this.setState({ search: e.target.value });
  }

  handleSelectAllRacers() {
    const { selectedRacers } = this.state;
    const { racers } = this.props;
    if (selectedRacers.length === racers.length) {
      this.setState({
        selectedRacers: []
      });
    } else {
      this.setState({
        selectedRacers: racers.map(racer => (racer.id))
      });
    }
  }

  handleRacerSelect(racer) {
    const { selectedRacers } = this.state;
    if (selectedRacers.indexOf(racer.id) !== -1) {
      this.setState({
        selectedRacers: selectedRacers.filter(id => id !== racer.id)
      });
    } else {
      this.setState({
        selectedRacers: [...selectedRacers, racer.id]
      });
    }
  }

  open() {
    const { search } = this.state;
    const { racerAttributes } = this.props;
    if (Object.keys(racerAttributes).length) {
      this.setState({
        newRacerName: search,
        previousSearch: search,
        search: '',
        showModal: true
      });
    } else {
      this.setState({
        newRacerName: search,
        search: ''
      }, () => {
        this.createRacer();
      });
    }
  }

  cancel() {
    this.setState({
      search: this.state.previousSearch,
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      showModal: false
    });
  }

  createRacer() {
    const { newRacerName, newRacerAttributes } = this.state;
    const { addRacer } = this.props;
    if (newRacerName.trim().length) {
      addRacer({
        name: newRacerName.trim(),
        ...newRacerAttributes
      });
      this.setState({
        search: '',
        previousSearch: '',
        newRacerName: '',
        newRacerAttributes: {},
        showModal: false
      });
    }
  }

  render() {
    let input;
    const { search, selectedRacers } = this.state;
    const {
      racerAttributes, addRaces, racers, bikes, removeRacers
    } = this.props;

    return (

          Roster

                Racers

                  <input
                    type="text"
                    className="form-control"
                    style={{
                      width: 'calc(100% - 41px)'
                    }}
                    placeholder="Search for or create a new racer..."
                    autoFocus="true"
                    value={this.state.search}
                    onChange={this.handleSearch.bind(this)}
                  />
                  <i
                    className={`material-icons md-36 unselectable ${style.addRacerBtn}`}
                    tabIndex="0"
                    role="button"
                    onClick={() => { this.open(); }}
                    onKeyDown={(e) => {
                      if (e.keyCode === 13) {
                        this.open();
                      }
                    }}
                  >
                    add_box

 11 ? 'scroll' : undefined
              }}
            >

                    <th
                      className={`${style.racersHeader} unselectable`}
                      onClick={() => this.handleSelectAllRacers()}
                    >

                        {selectedRacers.length === racers.length && racers.length ?
                          'check_box' : 'check_box_outline_blank'
                        }

                    <th className={`${style.racersHeader} unselectable`}>Name
                    {Object.keys(racerAttributes).map(key => (
                      <th
                        className={`${style.racersHeader} unselectable`}
                        key={`${key}-roster-header`}
                      >
                        {key}

                    ))}
                    <th className={`${style.racersHeader} unselectable`}>Time

                  {racers.filter((racer) => {
                    if (search && search && search.trim()) {
                      return racer.name.toLowerCase().indexOf(search.trim().toLowerCase()) !== -1;
                    }
                    return true;
                  }).map(racer => (
                    <RosterRacer
                      key={`racer-${racer.id}`}
                      racer={racer}
                      racerAttributes={racerAttributes}
                      selected={(selectedRacers.indexOf(racer.id) > -1)}
                      onClick={() => this.handleRacerSelect(racer)}
                    />
                  ))}

              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    removeRacers(selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Delete Selected
              </button>
              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    addRaces(bikes, selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Add Race with selected Racers
              </button>

        <RaceSetup {...this.props} />

        <Modal
          show={this.state.showModal}
          onHide={() => { this.cancel(); }}
          animation={false}
        >
          <Modal.Header closeButton>
            <Modal.Title>Add Racer</Modal.Title>
          </Modal.Header>
          <Modal.Body>

              Name
              <input
                className="form-control"
                type="text"
                id="newRacerName"
                value={this.state.newRacerName}
                onChange={(e) => {
                  this.setState({ newRacerName: e.target.value });
                }}
              />

            {
              Object.keys(racerAttributes).map(key => (
                racerAttributeRadioGroup(key, racerAttributes[key], (e) => {
                  const { newRacerAttributes } = this.state;
                  this.setState({
                    newRacerAttributes: Object.assign(
                      {},
                      newRacerAttributes,
                      { [key]: e.target.value }
                    )
                  });
                })
              ))
            }
          </Modal.Body>
          <Modal.Footer>
            <button
              className="btn btn-default"
              onClick={() => { this.cancel(); }}
            >
              Cancel
            </button>
            <button
              className="btn btn-primary"
              onClick={() => {
                this.createRacer();
              }}
            >
              Save
            </button>
          </Modal.Footer>
        </Modal>

    );
  }
}
<commit_msg>Quality of Life change to have enter create racer on roster page<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormGroup, Modal, Radio } from 'react-bootstrap';
import RosterRacer from './Racer';
import RaceSetup from './RaceSetup';
import style from './roster.css';

const racerAttributeRadioGroup = (key, options, onChange) => (
  <FormGroup
    key={`${key}-option-group`}
    style={{
      float: 'left',
      display: 'inline-block',
      width: '50%',
      paddingLeft: '5px'
    }}
  >
    {key}
    {options.map(option => (
      <Radio
        key={`${option}-radio-btn`}
        name={key}
        value={option}
        onChange={onChange}
      >
        {option}
      </Radio>
    ))}
  </FormGroup>
);

export default class Roster extends Component {
  static propTypes = {
    bikes: PropTypes.array.isRequired,
    races: PropTypes.array.isRequired,
    addRaces: PropTypes.func.isRequired,
    racers: PropTypes.array.isRequired,
    racerAttributes: PropTypes.object.isRequired,
    addRacer: PropTypes.func.isRequired,
    removeRacers: PropTypes.func.isRequired,
    editRacer: PropTypes.func
  };

  constructor(props, context) {
    super(props, context);
    this.state = {
      search: '',
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      selectedRacers: [],
      showModal: false
    };
  }

  handleSearch(e) {
    this.setState({ search: e.target.value });
  }

  handleSelectAllRacers() {
    const { selectedRacers } = this.state;
    const { racers } = this.props;
    if (selectedRacers.length === racers.length) {
      this.setState({
        selectedRacers: []
      });
    } else {
      this.setState({
        selectedRacers: racers.map(racer => (racer.id))
      });
    }
  }

  handleRacerSelect(racer) {
    const { selectedRacers } = this.state;
    if (selectedRacers.indexOf(racer.id) !== -1) {
      this.setState({
        selectedRacers: selectedRacers.filter(id => id !== racer.id)
      });
    } else {
      this.setState({
        selectedRacers: [...selectedRacers, racer.id]
      });
    }
  }

  open() {
    const { search } = this.state;
    const { racerAttributes } = this.props;
    if (Object.keys(racerAttributes).length) {
      this.setState({
        newRacerName: search,
        previousSearch: search,
        search: '',
        showModal: true
      });
    } else {
      this.setState({
        newRacerName: search,
        search: ''
      }, () => {
        this.createRacer();
      });
    }
  }

  cancel() {
    this.setState({
      search: this.state.previousSearch,
      previousSearch: '',
      newRacerName: '',
      newRacerAttributes: {},
      showModal: false
    });
  }

  createRacer() {
    const { newRacerName, newRacerAttributes } = this.state;
    const { addRacer } = this.props;
    if (newRacerName.trim().length) {
      addRacer({
        name: newRacerName.trim(),
        ...newRacerAttributes
      });
      this.setState({
        search: '',
        previousSearch: '',
        newRacerName: '',
        newRacerAttributes: {},
        showModal: false
      });
    }
  }

  checkForEnterKey(e) {
    if (e.keyCode === 13) {
      this.open();
    }
  }

  render() {
    let input;
    const { search, selectedRacers } = this.state;
    const {
      racerAttributes, addRaces, racers, bikes, removeRacers
    } = this.props;

    return (

          Roster

                Racers

                  <input
                    type="text"
                    className="form-control"
                    style={{
                      width: 'calc(100% - 41px)'
                    }}
                    placeholder="Search for or create a new racer..."
                    autoFocus="true"
                    value={this.state.search}
                    onChange={this.handleSearch.bind(this)}
                    onKeyUp={this.checkForEnterKey.bind(this)}
                  />
                  <i
                    className={`material-icons md-36 unselectable ${style.addRacerBtn}`}
                    tabIndex="0"
                    role="button"
                    onClick={() => { this.open(); }}
                    onKeyDown={this.checkForEnterKey.bind(this)}
                  >
                    add_box

 11 ? 'scroll' : undefined
              }}
            >

                    <th
                      className={`${style.racersHeader} unselectable`}
                      onClick={() => this.handleSelectAllRacers()}
                    >

                        {selectedRacers.length === racers.length && racers.length ?
                          'check_box' : 'check_box_outline_blank'
                        }

                    <th className={`${style.racersHeader} unselectable`}>Name
                    {Object.keys(racerAttributes).map(key => (
                      <th
                        className={`${style.racersHeader} unselectable`}
                        key={`${key}-roster-header`}
                      >
                        {key}

                    ))}
                    <th className={`${style.racersHeader} unselectable`}>Time

                  {racers.filter((racer) => {
                    if (search && search && search.trim()) {
                      return racer.name.toLowerCase().indexOf(search.trim().toLowerCase()) !== -1;
                    }
                    return true;
                  }).map(racer => (
                    <RosterRacer
                      key={`racer-${racer.id}`}
                      racer={racer}
                      racerAttributes={racerAttributes}
                      selected={(selectedRacers.indexOf(racer.id) > -1)}
                      onClick={() => this.handleRacerSelect(racer)}
                    />
                  ))}

              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    removeRacers(selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Delete Selected
              </button>
              <button
                className={`btn btn-default${(selectedRacers.length > 0 ? '' : ' disabled')}`}
                onClick={() => {
                  if (selectedRacers.length > 0) {
                    addRaces(bikes, selectedRacers);
                    this.setState({
                      selectedRacers: []
                    });
                  }
                }}
              >
                Add Race with selected Racers
              </button>

        <RaceSetup {...this.props} />

        <Modal
          show={this.state.showModal}
          onHide={() => { this.cancel(); }}
          animation={false}
        >
          <Modal.Header closeButton>
            <Modal.Title>Add Racer</Modal.Title>
          </Modal.Header>
          <Modal.Body>

              Name
              <input
                className="form-control"
                type="text"
                id="newRacerName"
                value={this.state.newRacerName}
                onChange={(e) => {
                  this.setState({ newRacerName: e.target.value });
                }}
              />

            {
              Object.keys(racerAttributes).map(key => (
                racerAttributeRadioGroup(key, racerAttributes[key], (e) => {
                  const { newRacerAttributes } = this.state;
                  this.setState({
                    newRacerAttributes: Object.assign(
                      {},
                      newRacerAttributes,
                      { [key]: e.target.value }
                    )
                  });
                })
              ))
            }
          </Modal.Body>
          <Modal.Footer>
            <button
              className="btn btn-default"
              onClick={() => { this.cancel(); }}
            >
              Cancel
            </button>
            <button
              className="btn btn-primary"
              onClick={() => {
                this.createRacer();
              }}
            >
              Save
            </button>
          </Modal.Footer>
        </Modal>

    );
  }
}
<|endoftext|>


<commit_before>
import Ember from 'ember';

var defaultWidgetConfiguration = {
    model: {
        index: {
            widgets: [
                {type: 'model-display'}
            ]
        },
        new: {
            widgets: [
                {type: 'model-form'}
            ]
        },
        edit: {
            widgets: [
                {type: 'model-form'}
            ]
        }
    },
    collection: {
        index: {
            widgets: [
                {type: 'collection-list'}
            ]
        }
    }
};

export default Ember.Component.extend({

    routeModel: null,
    application: null,

    /** the routeName is used to fetch the related widget
     * configuration from the structure (si `_widgetsConfig`)
     */
    routeName: null,
    modelMeta: Ember.computed.alias('routeModel.meta'),
    modelType: Ember.computed.alias('modelMeta.modelType'),

    /** if true, and the grid don't have a `widget-outlet` (`hasOutlet` is `false`)
     * then the grid will append an outlet
     */
    yieldOutlet: false,

    hasOutlet: function() {
        return this.get('widgetsConfigList').mapBy('isOutlet').compact().length > 0;
    }.property('widgetsConfigList.@each.isOutlet'),

    getWidgetComponentName: function(widgetName) {
        var dasherizedModelType = this.get('modelType').dasherize();
        var componentName = dasherizedModelType+'-widget-'+widgetName;

        console.log('1) -', componentName);

        if (!this.container.resolve('component:'+componentName)) {
            componentName = 'widget-'+widgetName;
            console.log('2) -', componentName);
        }

        if (!this.container.resolve('component:'+componentName)) {
            console.error('component', componentName, 'not found, please create it.');
        }

        console.log('#) -', componentName);
        return componentName;
    },

    _getWidgetsConfigList: function() {

        // we need the "widget's path" from the routeName:
        // user.model.index -> model.index
        var path = this.get('routeName').split('.').slice(1).join('.');

        // get the widgets configuration from the structure
        var widgetsConfig = this.get('modelMeta.views.'+path);

        // if no configurations are found, take the default one
        if (!widgetsConfig) {
            widgetsConfig = Ember.get(defaultWidgetConfiguration, path);
        }

        var widgetsConfigList = Ember.get(widgetsConfig, 'widgets');
        return Ember.A(widgetsConfigList);
    },

    widgetsConfigList: function() {
        var results = Ember.A();
        var that = this;

        var _widgetsConfig = this._getWidgetsConfigList();

        _widgetsConfig.forEach(function(widget) {

            // we will need the full component name, let's add it here
            var componentName = that.getWidgetComponentName(widget.type);
            widget.componentName = componentName;
            var widgetConf = Ember.Object.create(widget);

            if (widgetConf.get('type') === 'outlet') {
                widgetConf.set('isOutlet', true);
            }

            results.pushObject(widgetConf);
        });
        return results;
    }.property('routeName'),

    actions: {
        // forwards the actions to the parent component (until the controller)
        toControllerAction: function(actionName) {
            this.sendAction('toControllerAction', actionName);
        }
    }

    // _initializeGrid: function() {
    // }.on('didInsertElement')

});
<commit_msg>clean up<commit_after>
import Ember from 'ember';

var defaultWidgetConfiguration = {
    model: {
        index: {
            widgets: [
                {type: 'model-display'}
            ]
        },
        new: {
            widgets: [
                {type: 'model-form'}
            ]
        },
        edit: {
            widgets: [
                {type: 'model-form'}
            ]
        }
    },
    collection: {
        index: {
            widgets: [
                {type: 'collection-list'}
            ]
        }
    }
};

export default Ember.Component.extend({

    routeModel: null,
    application: null,

    /** the routeName is used to fetch the related widget
     * configuration from the structure (si `_widgetsConfig`)
     */
    routeName: null,
    modelMeta: Ember.computed.alias('routeModel.meta'),
    modelType: Ember.computed.alias('modelMeta.modelType'),

    /** if true, and the grid don't have a `widget-outlet` (`hasOutlet` is `false`)
     * then the grid will append an outlet
     */
    yieldOutlet: false,

    hasOutlet: function() {
        return this.get('widgetsConfigList').mapBy('isOutlet').compact().length > 0;
    }.property('widgetsConfigList.@each.isOutlet'),

    /** return the name of the widget composant.
     * It not composant is found for a specific model,
     * fallback to the generic one (if possible).
     *
     * Example:
     *    - if `user-widget-model-form` doesn't resolve
     *    - use `widget-model-form`
     */
    getWidgetComponentName: function(widgetName) {
        var dasherizedModelType = this.get('modelType').dasherize();
        var componentName = dasherizedModelType+'-widget-'+widgetName;

        if (!this.container.resolve('component:'+componentName)) {
            componentName = 'widget-'+widgetName;
        }

        if (!this.container.resolve('component:'+componentName)) {
            console.error('component', componentName, 'not found, please create it.');
        }

        return componentName;
    },

    _getWidgetsConfigList: function() {

        // we need the "widget's path" from the routeName:
        // user.model.index -> model.index
        var path = this.get('routeName').split('.').slice(1).join('.');

        // get the widgets configuration from the structure
        var widgetsConfig = this.get('modelMeta.views.'+path);

        // if no configurations are found, take the default one
        if (!widgetsConfig) {
            widgetsConfig = Ember.get(defaultWidgetConfiguration, path);
        }

        var widgetsConfigList = Ember.get(widgetsConfig, 'widgets');
        return Ember.A(widgetsConfigList);
    },

    widgetsConfigList: function() {
        var results = Ember.A();
        var that = this;

        var _widgetsConfig = this._getWidgetsConfigList();

        _widgetsConfig.forEach(function(widget) {

            // we will need the full component name, let's add it here
            var componentName = that.getWidgetComponentName(widget.type);
            widget.componentName = componentName;
            var widgetConf = Ember.Object.create(widget);

            if (widgetConf.get('type') === 'outlet') {
                widgetConf.set('isOutlet', true);
            }

            results.pushObject(widgetConf);
        });
        return results;
    }.property('routeName'),

    actions: {
        // forwards the actions to the parent component (until the controller)
        toControllerAction: function(actionName) {
            this.sendAction('toControllerAction', actionName);
        }
    }

    // _initializeGrid: function() {
    // }.on('didInsertElement')

});
<|endoftext|>


<commit_before>import Map from 'ti.map';

let location,
		firstOpenDone;

/**
 *  Constructor
 */
(function constructor(args) {
	location = require('/locations').getCurrentLocation();
	firstOpenDone = false;

	if (OS_ANDROID) {
  		Alloy.Globals.setAndroidBackButton($.index);
  }

	setMap();
	setUI();
})(arguments[0] || {});

function setMap() {
	if (!Alloy.Globals.isGooglePlayServicesAvailable) {
		Ti.API.warn('Google Maps is not configured correctly. Please set your API key in the tiapp.xml, clean and try again!');
		return;
	}

	const pin = Map.createAnnotation({
		latitude: location.location.lat,
		longitude: location.location.lon,
		title: location.title,
		subtitle: location.location.address
	});
	$.map.addAnnotation(pin);

	$.map.setRegion({
		latitude: location.location.lat,
		longitude: location.location.lon,
		latitudeDelta : 0.05,
		longitudeDelta : 0.05
	});
}

function askForRoute() {
	const dia = Ti.UI.createAlertDialog({
		title: L('show_route'),
		message: L('show_route_msg'),
		buttonNames: [L('cancel'), L('show')],
		preferred: 1,
		cancel: 0
	});

	dia.addEventListener('click', (e) => {
		if (e.index === 1) {
			const prefix = (OS_ANDROID) ? 'http://maps.google.com/?' : 'maps:';
			Ti.Platform.openURL(prefix + 'f=d&hl=en&geocode=&saddr=&sll=&daddr=' +  encodeURIComponent(location.location.address))
		}
	});

	dia.show();
}

function setUI() {
	const openings = location.openings;
	let sections = [];

	for (let i = 0; i < openings.length;i++) {
		const opening = openings[i];
		let items = [];

		let attrs = {
			properties: {
				height: 43,
				title: opening.time
			}
		};

		if (OS_ANDROID) {
			attrs = {
				properties: Object.assign(attrs.properties, {
					left: 15,
					color: '#000',
					font: {
						fontSize: 15
					}
				})
			};
		}

		const section = Ti.UI.createListSection({
			headerTitle: opening.date,
			items: [attrs]
		});
		sections.push(section);
	}

	$.list.setSections(sections);
}

function selectAnnotation(e) {
	if (!Alloy.Globals.isGooglePlayServicesAvailable || firstOpenDone) {
		return;
	}

	firstOpenDone = true;

	if (OS_IOS) {
		$.map.visibleMapRect = {
			animated: true,
			padding: {
				top: 50
			}
		};
	}

	$.map.selectAnnotation($.map.annotations[0]);
}
<commit_msg>Be less dump<commit_after>import Map from 'ti.map';

let location,
		firstOpenDone;

/**
 *  Constructor
 */
(function constructor(args) {
	location = require('/locations').getCurrentLocation();
	firstOpenDone = false;

	if (OS_ANDROID) {
  		Alloy.Globals.setAndroidBackButton($.index);
  }

	setMap();
	setUI();
})(arguments[0] || {});

function setMap() {
	if (OS_ANDROID && !Alloy.Globals.isGooglePlayServicesAvailable) {
		Ti.API.warn('Google Maps is not configured correctly. Please set your API key in the tiapp.xml, clean and try again!');
		return;
	}

	const pin = Map.createAnnotation({
		latitude: location.location.lat,
		longitude: location.location.lon,
		title: location.title,
		subtitle: location.location.address
	});
	$.map.addAnnotation(pin);

	$.map.setRegion({
		latitude: location.location.lat,
		longitude: location.location.lon,
		latitudeDelta : 0.05,
		longitudeDelta : 0.05
	});
}

function askForRoute() {
	const dia = Ti.UI.createAlertDialog({
		title: L('show_route'),
		message: L('show_route_msg'),
		buttonNames: [L('cancel'), L('show')],
		preferred: 1,
		cancel: 0
	});

	dia.addEventListener('click', (e) => {
		if (e.index === 1) {
			const prefix = (OS_ANDROID) ? 'http://maps.google.com/?' : 'maps:';
			Ti.Platform.openURL(prefix + 'f=d&hl=en&geocode=&saddr=&sll=&daddr=' +  encodeURIComponent(location.location.address))
		}
	});

	dia.show();
}

function setUI() {
	const openings = location.openings;
	let sections = [];

	for (let i = 0; i < openings.length;i++) {
		const opening = openings[i];
		let items = [];

		let attrs = {
			properties: {
				height: 43,
				title: opening.time
			}
		};

		if (OS_ANDROID) {
			attrs = {
				properties: Object.assign(attrs.properties, {
					left: 15,
					color: '#000',
					font: {
						fontSize: 15
					}
				})
			};
		}

		const section = Ti.UI.createListSection({
			headerTitle: opening.date,
			items: [attrs]
		});
		sections.push(section);
	}

	$.list.setSections(sections);
}

function selectAnnotation(e) {
	if (!Alloy.Globals.isGooglePlayServicesAvailable || firstOpenDone) {
		return;
	}

	firstOpenDone = true;

	if (OS_IOS) {
		$.map.visibleMapRect = {
			animated: true,
			padding: {
				top: 50
			}
		};
	}

	$.map.selectAnnotation($.map.annotations[0]);
}
<|endoftext|>


<commit_before>var map = new maptalks.Map('map', {
  center:     [-0.113049,51.498568],
  zoom:  6,
  pitch : 40,
  attribution: {
    content: '$(attribution), © BoudlessGeo'
  },
  // add 2 TileLayers with a GroupTileLayer
  baseLayer : new maptalks.GroupTileLayer('base', [
    new maptalks.TileLayer('tile2', {
      urlTemplate: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_nolabels/{z}/{x}/{y}.png',
      subdomains  : ['a','b','c','d']
    }),

    new maptalks.WMSTileLayer('wms', {
      'urlTemplate' : 'https://demo.boundlessgeo.com/geoserver/ows',
      'crs' : 'EPSG:3857',
      'layers' : 'ne:ne',
      'styles' : '',
      'version' : '1.3.0',
      'format': 'image/png',
      'transparent' : true,
      'uppercase' : true,
      'opacity' : 0.5
    })
  ])
});
<commit_msg>fix grouptilelayer<commit_after>var map = new maptalks.Map('map', {
  center:     [-0.113049,51.498568],
  zoom:  6,
  pitch : 40,
  attribution: {
    content: '$(attribution), © BoudlessGeo'
  },
  // add 2 TileLayers with a GroupTileLayer
  baseLayer : new maptalks.GroupTileLayer('base', [
    new maptalks.TileLayer('tile2', {
      urlTemplate: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_nolabels/{z}/{x}/{y}.png',
      subdomains  : ['a','b','c','d']
    }),

    new maptalks.WMSTileLayer('wms', {
      'urlTemplate' : 'https://demo.boundlessgeo.com/geoserver/ows',
      'crs' : 'EPSG:3857',
      'layers' : 'ne:ne',
      'styles' : '',
      'version' : '1.3.0',
      'format': 'image/png',
      'transparent' : true,
      'uppercase' : true
    })
  ])
});
<|endoftext|>


<commit_before>/**
 * Created by Student on 11/18/2015.
 */

(function(){
    //var players = [
    //    { id: 1, name: "Gaurav", image: "a.png", bb: 9, gb: 8},
    //    { id: 2, name: "Rajesh", image: "b.png", bb: 7, gb: 6},
    //    { id: 3, name: "Jason", image: "c.png", bb: 4, gb: 5},
    //    { id: 4, name: "Mihaly", image: "d.png", bb: 3, gb: 4}
    //];

    var players = [
        { id: 1, name: "Gaurav", image: "http://www.wallhogs.com/images/products/orig/1369.gif", bb: 9, gb: 9, adr: "Mumbai, India"
        },
        { id: 2, name: "Rajesh", image: "http://images.supersport.com/2015/7/Paul-Dunne-150720-Waves-G-300.jpg", bb: 7, gb: 7, adr: "Bear, Delaware"},
        { id : 3, name : "Jason", image: "http://www.clipartbest.com/cliparts/7ia/Kqy/7iaKqye5T.png", bb : 4, gb : 5, adr:"Los Vegas, Nevada"},
        {
            id: 4, name: "Mihaly", image: "http://www.sportspectator.com/fancentral/golf/GolfPlayer.jpg", bb: 3, gb: 4, adr:"Columbus, Ohio"}
    ];

    var isBaseball = false;
    var index=-1;

    var playerFactory=function(){
        var factory = {};
        factory.getPlayers = function () {
            return players;
        };
        factory.setIsBaseball = function (val) {
            isBaseball = val;
        };

        factory.getIsBaseball = function () {
            return isBaseball;
        };

        factory.setIndex=function(vIndex){
            index = vIndex;
        };

        factory.getIndex = function(){
            return index;
        };

        return factory;
    };

    angular.module('myApp.view3').factory('view3Factory', playerFactory);
    angular.module('myApp.view2').factory('view2Factory', playerFactory);
    angular.module('myApp.view1').factory('view1Factory', playerFactory);
}());

<commit_msg>Jason images<commit_after>/**
 * Created by Student on 11/18/2015.
 */

(function(){
    //var players = [
    //    { id: 1, name: "Gaurav", image: "a.png", bb: 9, gb: 8},
    //    { id: 2, name: "Rajesh", image: "b.png", bb: 7, gb: 6},
    //    { id: 3, name: "Jason", image: "c.png", bb: 4, gb: 5},
    //    { id: 4, name: "Mihaly", image: "d.png", bb: 3, gb: 4}
    //];

    var players = [
        { id: 1, name: "Gaurav", image: "http://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Derek_Jeter_batting_stance_allison.jpg/250px-Derek_Jeter_batting_stance_allison.jpg", bb: 9, gb: 9, adr: "Mumbai, India"
        },
        { id: 2, name: "Rajesh", image: "http://www.intotherough.co.uk/assets/_files/images/oct_08/itr__1223643724_vijay_singh_golf_equipment.jpg", bb: 7, gb: 7, adr: "Bear, Delaware"},
        { id : 3, name : "Jason", image: "http://a4.espncdn.com/photo/2014/0821/mlb_pete_rose_01.jpg", bb:10, gb:6, adr:"Las Vegas, Nevada"},
        {
            id: 4, name: "Mihaly", image: "http://www.nosolodeportes.com/images/2009/02/ernie-els.jpg", bb: 3, gb: 4, adr:"Columbus, Ohio"}
    ];

    var isBaseball = false;
    var index=-1;

    var playerFactory=function(){
        var factory = {};
        factory.getPlayers = function () {
            return players;
        };
        factory.setIsBaseball = function (val) {
            isBaseball = val;
        };

        factory.getIsBaseball = function () {
            return isBaseball;
        };

        factory.setIndex=function(vIndex){
            index = vIndex;
        };

        factory.getIndex = function(){
            return index;
        };

        return factory;
    };

    angular.module('myApp.view3').factory('view3Factory', playerFactory);
    angular.module('myApp.view2').factory('view2Factory', playerFactory);
    angular.module('myApp.view1').factory('view1Factory', playerFactory);
}());

<|endoftext|>


<commit_before>import ReactDOM from 'react-dom';

const ItemTargetHelper = {

  /**
   * Helper method for when drag and drop is enabled for
   * items grouped together vertically e.g. a list, or
   * a table.
   */
  onHoverUpDown(props, monitor, component) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return;
    }

    // Determine rectangle on screen
    const el = ReactDOM.findDOMNode(component); // eslint-disable-line react/no-find-dom-node
    const hoverBoundingRect = el.getBoundingClientRect();

    // Get vertical middle
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;

    // Determine mouse position
    const clientOffset = monitor.getClientOffset();

    // Get pixels to the top
    const hoverClientY = clientOffset.y - hoverBoundingRect.top;

    // Only perform the move when the mouse has crossed half of the items height
    // When dragging downwards, only move when the cursor is below 50%
    // When dragging upwards, only move when the cursor is above 50%

    // Dragging downwards
    if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
      return;
    }

    // Dragging upwards
    if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
      return;
    }

    // Time to actually perform the action
    const onDrag = props.onDrag || component.context.dragAndDropOnDrag;
    onDrag(dragIndex, hoverIndex);
    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    monitor.getItem().index = hoverIndex;
  }

};

export default ItemTargetHelper;
<commit_msg>(FE-1569) dnd/item-target: remove "50% height" conditional logic<commit_after>import ReactDOM from 'react-dom';

const ItemTargetHelper = {

  /**
   * Helper method for when drag and drop is enabled for
   * items grouped together vertically e.g. a list, or
   * a table.
   */
  onHoverUpDown(props, monitor, component) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return;
    }

    // Time to actually perform the action
    const onDrag = props.onDrag || component.context.dragAndDropOnDrag;
    onDrag(dragIndex, hoverIndex);
    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    monitor.getItem().index = hoverIndex;
  }

};

export default ItemTargetHelper;
<|endoftext|>


<commit_before>/*
 *     (C) Copyright 2012-2013 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global EzWebExt, Wirecloud*/

Wirecloud.location = {
    'domain': document.location.protocol + '//' + document.location.host,
    'protocol': document.location.protocol.substr(0, document.location.protocol.length - 1),
    'host': document.location.host
};

(function () {

    "use strict";

    var setRequestHeaders = function setRequestHeaders() {
        var headers, name;

        headers = EzWebExt.merge({
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
        }, this.options.requestHeaders);

        if (!('Content-Type' in headers) && this.options.contentType != null) {
            headers['Content-Type'] = this.options.contentType;
            if (this.options.encoding != null) {
                headers['Content-Type'] += '; charset=' + this.options.encoding;
            }
        }

        for (name in headers) {
            this.transport.setRequestHeader(name, headers[name]);
        }
    };

    var onReadyStateChange = function onReadyStateChange() {
        if (this.transport.readyState == 4) {

            var response = new Response(this);

            try {
                if (('on' + response.status) in this.options) {
                    this.options['on' + response.status](response);
                } else if (this.options.onSuccess && (response.status >= 200 && response.status < 300)) {
                    this.options.onSuccess(response);
                } else if (this.options.onFailure) {
                    this.options.onFailure(response);
                }
            } catch (e) {
            }

            if (this.options.onComplete) {
                try {
                    this.options.onComplete();
                } catch (e) {}
            }
        }
    };

    var Response = function Response(request) {
        Object.defineProperties(this, {
            'request': {value: request},
            'transport': {value: request.transport},
            'status': {value: request.transport.status},
            'statusText': {value: request.transport.statusText},
            'response': {value: request.transport.response},
            'responseXML': {value: request.transport.responseXML}
        });

        if (request.options.responseType == null || request.options.responseType === '') {
            Object.defineProperty(this, 'responseText', {value: request.transport.responseText});
        }
    };

    Response.prototype.getHeader = function getHeader(name) {
        try {
            return this.transport.getResponseHeader(name);
        } catch (e) { return null; }
    };

    Response.prototype.getAllResponseHeaders = function getAllResponseHeaders() {
        return this.transport.getAllResponseHeaders();
    };

    var toQueryString = function toQueryString(parameters) {
        var key, query = '';

        if (typeof parameters === 'string') {
            return parameters;
        }

        for (key in parameters) {
            query += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]);
        }

        return query.substr(1);
    };

    var Request = function Request(url, options) {
        this.url = url;
        this.options = EzWebExt.merge({
            method:       'POST',
            asynchronous: true,
            responseType: null,
            contentType:  null,
            encoding:     null,
            postBody:     null
        }, options);

        if (this.options.onSuccess != null && typeof this.options.onSuccess !== 'function') {
            throw new TypeError('Invalid onSuccess callback');
        }
        if (this.options.onFailure != null && typeof this.options.onFailure !== 'function') {
            throw new TypeError('Invalid onFailure callback');
        }
        this.method = this.options.method.toUpperCase();

        if (this.options.parameters != null && (typeof this.options.parameters === 'string' || typeof this.options.parameters === 'object')) {
            if (['PUT', 'POST'].indexOf(this.method) !== -1 && this.options.postBody == null) {
                this.postBody = toQueryString(this.options.parameters);
                if (this.options.contentType == null) {
                    this.options.contentType = 'application/x-www-form-urlencoded';
                }
                if (this.options.encoding == null) {
                    this.options.encoding = 'UTF-8';
                }
            } else if (this.method === 'GET') {
                if (this.url.indexOf('?') !== -1) {
                    this.url += '&' + toQueryString(this.options.parameters);
                }  else {
                    this.url += '?' + toQueryString(this.options.parameters);
                }
            }
        }

        this.transport = new XMLHttpRequest();
        this.transport.open(this.options.method, this.url, this.options.asynchronous);
        if (this.options.responseType) {
            this.transport.responseType = this.options.responseType;
        }
        this.transport.addEventListener('readystatechange', onReadyStateChange.bind(this), true);
        setRequestHeaders.call(this);
        this.transport.send(this.options.postBody);
    };

    var io = {};

    io.buildProxyURL = function buildProxyURL(url, options) {
        var final_url, protocolEnd, link, forceProxy, hostStart, pathStart, protocol,
            host, rest;

        if (options == null) {
            options = {};
        }

        forceProxy = !!options.forceProxy;

        if (url.length > 4 && url.indexOf('www.') === 0) {
            url = 'http://' + url;
        }

        protocol = Wirecloud.location.protocol;
        host = Wirecloud.location.host;

        protocolEnd = url.indexOf('://');
        if (protocolEnd !== -1) {
            hostStart = protocolEnd + 3;
            pathStart = url.indexOf('/', hostStart);
            if (pathStart === -1) {
                pathStart = url.length;
            }

            protocol = url.substr(0, protocolEnd);
            host = url.substr(hostStart, pathStart - hostStart);
            rest = url.substring(pathStart);
            final_url = url;
        } else {
            if (url.charAt(0) === '/') {
                rest = url;
            } else {
                rest = '/' + url;
            }

            if (!forceProxy) {
                final_url = Wirecloud.location.domain + rest;
            }
        }

        if (forceProxy || (options.supportsAccessControl !== true && (protocol !== Wirecloud.location.protocol || host !== Wirecloud.location.host))) {
            final_url = Wirecloud.location.domain +
                Wirecloud.URLs.PROXY.evaluate({protocol: protocol, domain: host, path: rest});
        }

        return final_url;
    };

    io.makeRequest = function makeRequest(url, options) {
        var handlerRegExp, key;

        if (options != null && options.context != null) {
            handlerRegExp = new RegExp(/^on(?:Create|Complete|Exception|Failure|Interactive|Loaded|Loading|Success|Uninitialized|\d{3})$/);
            for (key in options) {
                if (handlerRegExp.test(key) && typeof options[key] === 'function') {
                    options[key] = options[key].bind(options.context);
                }
            }
        }

        return new Request(Wirecloud.io.buildProxyURL(url, options), options);
    };

    Wirecloud.io = io;

})();
<commit_msg>Add responseXML attribute to the response only when responseType == ''<commit_after>/*
 *     (C) Copyright 2012-2013 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global EzWebExt, Wirecloud*/

Wirecloud.location = {
    'domain': document.location.protocol + '//' + document.location.host,
    'protocol': document.location.protocol.substr(0, document.location.protocol.length - 1),
    'host': document.location.host
};

(function () {

    "use strict";

    var setRequestHeaders = function setRequestHeaders() {
        var headers, name;

        headers = EzWebExt.merge({
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
        }, this.options.requestHeaders);

        if (!('Content-Type' in headers) && this.options.contentType != null) {
            headers['Content-Type'] = this.options.contentType;
            if (this.options.encoding != null) {
                headers['Content-Type'] += '; charset=' + this.options.encoding;
            }
        }

        for (name in headers) {
            this.transport.setRequestHeader(name, headers[name]);
        }
    };

    var onReadyStateChange = function onReadyStateChange() {
        if (this.transport.readyState == 4) {

            var response = new Response(this);

            try {
                if (('on' + response.status) in this.options) {
                    this.options['on' + response.status](response);
                } else if (this.options.onSuccess && (response.status >= 200 && response.status < 300)) {
                    this.options.onSuccess(response);
                } else if (this.options.onFailure) {
                    this.options.onFailure(response);
                }
            } catch (e) {
            }

            if (this.options.onComplete) {
                try {
                    this.options.onComplete();
                } catch (e) {}
            }
        }
    };

    var Response = function Response(request) {
        Object.defineProperties(this, {
            'request': {value: request},
            'transport': {value: request.transport},
            'status': {value: request.transport.status},
            'statusText': {value: request.transport.statusText},
            'response': {value: request.transport.response}
        });

        if (request.options.responseType == null || request.options.responseType === '') {
            Object.defineProperties(this, {
                'responseText': {value: request.transport.responseText},
                'responseXML': {value: request.transport.responseXML}
            });
        }
    };

    Response.prototype.getHeader = function getHeader(name) {
        try {
            return this.transport.getResponseHeader(name);
        } catch (e) { return null; }
    };

    Response.prototype.getAllResponseHeaders = function getAllResponseHeaders() {
        return this.transport.getAllResponseHeaders();
    };

    var toQueryString = function toQueryString(parameters) {
        var key, query = '';

        if (typeof parameters === 'string') {
            return parameters;
        }

        for (key in parameters) {
            query += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]);
        }

        return query.substr(1);
    };

    var Request = function Request(url, options) {
        this.url = url;
        this.options = EzWebExt.merge({
            method:       'POST',
            asynchronous: true,
            responseType: null,
            contentType:  null,
            encoding:     null,
            postBody:     null
        }, options);

        if (this.options.onSuccess != null && typeof this.options.onSuccess !== 'function') {
            throw new TypeError('Invalid onSuccess callback');
        }
        if (this.options.onFailure != null && typeof this.options.onFailure !== 'function') {
            throw new TypeError('Invalid onFailure callback');
        }
        this.method = this.options.method.toUpperCase();

        if (this.options.parameters != null && (typeof this.options.parameters === 'string' || typeof this.options.parameters === 'object')) {
            if (['PUT', 'POST'].indexOf(this.method) !== -1 && this.options.postBody == null) {
                this.postBody = toQueryString(this.options.parameters);
                if (this.options.contentType == null) {
                    this.options.contentType = 'application/x-www-form-urlencoded';
                }
                if (this.options.encoding == null) {
                    this.options.encoding = 'UTF-8';
                }
            } else if (this.method === 'GET') {
                if (this.url.indexOf('?') !== -1) {
                    this.url += '&' + toQueryString(this.options.parameters);
                }  else {
                    this.url += '?' + toQueryString(this.options.parameters);
                }
            }
        }

        this.transport = new XMLHttpRequest();
        this.transport.open(this.options.method, this.url, this.options.asynchronous);
        if (this.options.responseType) {
            this.transport.responseType = this.options.responseType;
        }
        this.transport.addEventListener('readystatechange', onReadyStateChange.bind(this), true);
        setRequestHeaders.call(this);
        this.transport.send(this.options.postBody);
    };

    var io = {};

    io.buildProxyURL = function buildProxyURL(url, options) {
        var final_url, protocolEnd, link, forceProxy, hostStart, pathStart, protocol,
            host, rest;

        if (options == null) {
            options = {};
        }

        forceProxy = !!options.forceProxy;

        if (url.length > 4 && url.indexOf('www.') === 0) {
            url = 'http://' + url;
        }

        protocol = Wirecloud.location.protocol;
        host = Wirecloud.location.host;

        protocolEnd = url.indexOf('://');
        if (protocolEnd !== -1) {
            hostStart = protocolEnd + 3;
            pathStart = url.indexOf('/', hostStart);
            if (pathStart === -1) {
                pathStart = url.length;
            }

            protocol = url.substr(0, protocolEnd);
            host = url.substr(hostStart, pathStart - hostStart);
            rest = url.substring(pathStart);
            final_url = url;
        } else {
            if (url.charAt(0) === '/') {
                rest = url;
            } else {
                rest = '/' + url;
            }

            if (!forceProxy) {
                final_url = Wirecloud.location.domain + rest;
            }
        }

        if (forceProxy || (options.supportsAccessControl !== true && (protocol !== Wirecloud.location.protocol || host !== Wirecloud.location.host))) {
            final_url = Wirecloud.location.domain +
                Wirecloud.URLs.PROXY.evaluate({protocol: protocol, domain: host, path: rest});
        }

        return final_url;
    };

    io.makeRequest = function makeRequest(url, options) {
        var handlerRegExp, key;

        if (options != null && options.context != null) {
            handlerRegExp = new RegExp(/^on(?:Create|Complete|Exception|Failure|Interactive|Loaded|Loading|Success|Uninitialized|\d{3})$/);
            for (key in options) {
                if (handlerRegExp.test(key) && typeof options[key] === 'function') {
                    options[key] = options[key].bind(options.context);
                }
            }
        }

        return new Request(Wirecloud.io.buildProxyURL(url, options), options);
    };

    Wirecloud.io = io;

})();
<|endoftext|>


<commit_before>/*global angular */

/**
 * @ngdoc directive
 * @name TatUi.directive:messagesItem
 * @restrict AE
 * @description
 * display a route message
 */
angular.module('TatUi').directive('messagesStandardviewItem', function($compile) {
  'use strict';

  return {
    restrict: 'E',
    scope: {
      message: '=',
      topic: '=',
      isTopicDeletableMsg: '=',
      isTopicUpdatableMsg: '=',
      isTopicDeletableAllMsg: '=',
      isTopicUpdatableAllMsg: '=',
      isTopicRw: '='
    },
    replace: true,
    templateUrl: '../build/tatwebui-plugin-standardview/standardview/list/standardview-item.directive.html',
    controllerAs: 'ctrl',
    /**
     * @ngdoc controller
     * @name TatUi.controller:messagesItem
     * @requires TatUi.Authentication       Tat Authentication
     * @requires TatUi.TatEngineMessageRsc  Tat Engine Resource Message
     * @requires TatUi.TatEngine            Global Tat Engine service
     *
     * @description Directive controller
     */
    controller: function($scope, $rootScope, TatEngineMessageRsc,
      TatEngineMessagesRsc, TatEngine, TatMessage, Authentication) {
      var self = this;
      this.answerPanel = false;

      this.canDoneMessage = false;
      this.canDeleteFromTasksMessage = false;
      this.canAddToTasksMessage = true;
      this.privateTasksTopic = 'Private/' + Authentication.getIdentity().username + '/Tasks';

      this.getBrightness = function(rgb) {
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(rgb);
        return result ?
          0.2126 * parseInt(result[1], 16) +
          0.7152 * parseInt(result[2], 16) +
          0.0722 * parseInt(result[3], 16) : 0;
      };

      /**
       * @ngdoc function
       * @name toggleTaskMessage
       * @methodOf TatUi.controller:messagesItem
       * @description create or remove a task from one message
       */
      this.addToTasksMessage = function(message) {
        TatEngineMessageRsc.update({
          'idReference': message._id,
          'action': 'task',
          'topic': message.topic
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          if (resp.message) {
            message.labels = resp.message.labels;
            message.dateUpdate = resp.message.dateUpdate;
          }
          self.canDeleteFromTasksMessage = true;
          self.canAddToTasksMessage = false;
          self.canDoneMessage = true;
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      this.deleteFromTasksMessage = function(message) {
        $scope.setInToDone = false;
        TatEngineMessageRsc.update({
          'idReference': message._id,
          'action': 'untask',
          'topic': message.topic
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          if (self.isTopicTasks) {
            message.hide = true;
          }
          if (resp.message) {
            message.labels = resp.message.labels;
            message.dateUpdate = resp.message.dateUpdate;
          }
          self.canDeleteFromTasksMessage = false;
          self.canAddToTasksMessage = true;
          self.canDoneMessage = false;
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      this.addLabelDone = function(message) {
        TatMessage.addLabel(message, $scope.topic.topic, "done", "#14892c", function() {
          TatMessage.addLabel(message,
            message.topic,
            "done:" + Authentication.getIdentity().username,
            "#14892c", //green,
            function() {
              self.removeLabel(message, "doing");
              self.removeLabel(message, "doing:"+Authentication.getIdentity().username, true);
            }
          );
        });
      };

      this.doneMessage = function(message) {
        $scope.setInToDone = false;
        TatEngineMessageRsc.update({
          'idReference': message._id,
          'action': 'untask',
          'topic': message.topic
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          if (self.isTopicTasks) {
            message.hide = true;
          }
          if (resp.message) {
            message.labels = resp.message.labels;
          }
          self.addLabelDone(message);
          self.canDeleteFromTasksMessage = false;
          self.canAddToTasksMessage = true;
          self.canDoneMessage = false;
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      /**
       * @ngdoc function
       * @name deleteMessage
       * @methodOf TatUi.controller:messagesItem
       * @description delete a message from a Private topic
       */
      this.deleteMessage = function(message) {
        TatEngineMessageRsc.delete({
          'idMessageToDelete': message._id,
          'cascade': 'cascade/'
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          message.hide = true;
          message.displayed = false;
        }, function(response) {
          TatEngine.displayReturn(response);
        });
      };

      /**
       * @ngdoc function
       * @name updateMessage
       * @methodOf TatUi.controller:messagesItem
       * @description Update a message
       */
      this.updateMessage = function(message) {
        message.updating = false;
        TatEngineMessageRsc.update({
          'topic': message.topic.substr(1),
          'idReference': message._id,
          'text': message.text,
          'action': 'update',
        }).$promise.then(function(resp) {
          message.text = resp.message.text;
        }, function(resp) {
          message.updating = true;
          TatEngine.displayReturn(resp);
        });
      };

      /**
       * @ngdoc function
       * @name hasLiked
       * @methodOf TatUi.controller:messagesItem
       * @description Define if the message is marked 'like'
       * @return {bool} If true, 'like'
       */
      this.hasLiked = function(message) {
        if (message && message.likers) {
          return _.includes(message.likers, Authentication.getIdentity().username);
        }
        return false;
      };

      /**
       * @ngdoc function
       * @name toggleLikeMessage
       * @methodOf TatUi.controller:messagesItem
       * @description toggle 'like' state on the message
       *
       */
      this.toggleLikeMessage = function(message) {
        var action = self.hasLiked(message) ? 'unlike' : 'like';
        TatEngineMessageRsc.update({
          'topic': message.topic.substr(1),
          'idReference': message._id,
          'action': action
        }).$promise.then(function(resp) {
          if (resp.message) {
            message.likers = resp.message.likers;
            message.nbLikes = resp.message.nbLikes;
          }
        }, function(err) {
          TatEngine.displayReturn(err);
        });
      };

      /**
       * @ngdoc function
       * @name removeLabel
       * @methodOf TatUi.controller:messagesItem
       * @description remove a label
       * @param {object} message Message on which to add a label
       * @param {object} label   Label {text} to remove
       */
      this.removeLabel = function(message, labelText) {
        if (!message.labels) {
          return;
        }

        TatEngineMessageRsc.update({
          'action': 'unlabel',
          'topic': message.topic.substr(1),
          'idReference': message._id,
          'text': labelText
        }).$promise.then(function(resp) {
          if (resp.message) {
            message.labels = resp.message.labels;
          }
          self.computeFlagsTask(message);
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      this.containsLabel = function(message, labelText) {
        if (message.inReplyOfIDRoot) {
          return false;
        }
        var r = false;
        if (message.labels) {
          for (var i = 0; i < message.labels.length; i++) {
            var l = message.labels[i];
            if (l.text === labelText) {
              return true;
            }
          }
        }
        return r;
      };

      this.refreshMsg = function(message) {
        message.loading = true;
        TatEngineMessagesRsc.list({
          topic: message.topic.substr(1),
          treeView: "onetree",
          idMessage: message._id,
          limit: 1,
          skip: 0
        }).$promise.then(function(data) {
          message.loading = false;
          if (!data.messages || data.messages.length != 1) {
            TatEngine.displayReturn("Invalid return while getting message");
            return
          }
          message.labels = data.messages[0].labels;
          message.tags = data.messages[0].tags;
          message.text = data.messages[0].text;
          message.nbLikes = data.messages[0].nbLikes;
          message.nbReplies = data.messages[0].nbReplies;
          message.nbVotesDown = data.messages[0].nbVotesDown;
          message.nbVotesUP = data.messages[0].nbVotesUP;
          message.dateCreation = data.messages[0].dateCreation;
          message.dateUpdate = data.messages[0].dateUpdate;
          message.replies = data.messages[0].replies;
        }, function(err) {
          message.loading = false;
          TatEngine.displayReturn(err);
        });
      }

      this.init = function(message) {
        self.refreshMsg(message);
        if ($scope.topic.topic.indexOf(self.privateTasksTopic) === 0) {
          self.isTopicTasks = true;
        }
        self.computeFlagsTask(message);
      };

      this.computeFlagsTask = function(message) {
        self.canDoneMessage = self.containsLabel(message, "doing:"+Authentication.getIdentity().username);
        self.canDeleteFromTasksMessage = self.containsLabel(message, "doing:"+Authentication.getIdentity().username);
        self.canAddToTasksMessage = !self.containsLabel(message, "doing:"+Authentication.getIdentity().username);
        if (self.containsLabel(message, "done")) {
          self.canDoneMessage = false;
        }

        if (message.topic && message.topic.indexOf("/" + self.privateTasksTopic) === 0) {
          $scope.isTopicDeletableMsg = true;
          $scope.isTopicDeletableAllMsg = true;
        }
      };

      this.init($scope.message);
    }
  };
});
<commit_msg>fix: fix delete<commit_after>/*global angular */

/**
 * @ngdoc directive
 * @name TatUi.directive:messagesItem
 * @restrict AE
 * @description
 * display a route message
 */
angular.module('TatUi').directive('messagesStandardviewItem', function($compile) {
  'use strict';

  return {
    restrict: 'E',
    scope: {
      message: '=',
      topic: '=',
      isTopicDeletableMsg: '=',
      isTopicUpdatableMsg: '=',
      isTopicDeletableAllMsg: '=',
      isTopicUpdatableAllMsg: '=',
      isTopicRw: '='
    },
    replace: true,
    templateUrl: '../build/tatwebui-plugin-standardview/standardview/list/standardview-item.directive.html',
    controllerAs: 'ctrl',
    /**
     * @ngdoc controller
     * @name TatUi.controller:messagesItem
     * @requires TatUi.Authentication       Tat Authentication
     * @requires TatUi.TatEngineMessageRsc  Tat Engine Resource Message
     * @requires TatUi.TatEngine            Global Tat Engine service
     *
     * @description Directive controller
     */
    controller: function($scope, $rootScope, TatEngineMessageRsc,
      TatEngineMessagesRsc, TatEngine, TatMessage, Authentication) {
      var self = this;
      this.answerPanel = false;

      this.canDoneMessage = false;
      this.canDeleteFromTasksMessage = false;
      this.canAddToTasksMessage = true;
      this.privateTasksTopic = 'Private/' + Authentication.getIdentity().username + '/Tasks';

      this.getBrightness = function(rgb) {
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(rgb);
        return result ?
          0.2126 * parseInt(result[1], 16) +
          0.7152 * parseInt(result[2], 16) +
          0.0722 * parseInt(result[3], 16) : 0;
      };

      /**
       * @ngdoc function
       * @name toggleTaskMessage
       * @methodOf TatUi.controller:messagesItem
       * @description create or remove a task from one message
       */
      this.addToTasksMessage = function(message) {
        TatEngineMessageRsc.update({
          'idReference': message._id,
          'action': 'task',
          'topic': message.topic
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          if (resp.message) {
            message.labels = resp.message.labels;
            message.dateUpdate = resp.message.dateUpdate;
          }
          self.canDeleteFromTasksMessage = true;
          self.canAddToTasksMessage = false;
          self.canDoneMessage = true;
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      this.deleteFromTasksMessage = function(message) {
        $scope.setInToDone = false;
        TatEngineMessageRsc.update({
          'idReference': message._id,
          'action': 'untask',
          'topic': message.topic
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          if (self.isTopicTasks) {
            message.hide = true;
          }
          if (resp.message) {
            message.labels = resp.message.labels;
            message.dateUpdate = resp.message.dateUpdate;
          }
          self.canDeleteFromTasksMessage = false;
          self.canAddToTasksMessage = true;
          self.canDoneMessage = false;
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      this.addLabelDone = function(message) {
        TatMessage.addLabel(message, $scope.topic.topic, "done", "#14892c", function() {
          TatMessage.addLabel(message,
            message.topic,
            "done:" + Authentication.getIdentity().username,
            "#14892c", //green,
            function() {
              self.removeLabel(message, "doing");
              self.removeLabel(message, "doing:"+Authentication.getIdentity().username, true);
            }
          );
        });
      };

      this.doneMessage = function(message) {
        $scope.setInToDone = false;
        TatEngineMessageRsc.update({
          'idReference': message._id,
          'action': 'untask',
          'topic': message.topic
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          if (self.isTopicTasks) {
            message.hide = true;
          }
          if (resp.message) {
            message.labels = resp.message.labels;
          }
          self.addLabelDone(message);
          self.canDeleteFromTasksMessage = false;
          self.canAddToTasksMessage = true;
          self.canDoneMessage = false;
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      /**
       * @ngdoc function
       * @name deleteMessage
       * @methodOf TatUi.controller:messagesItem
       * @description delete a message from a Private topic
       */
      this.deleteMessage = function(message) {
        TatEngineMessageRsc.delete({
          'fromTopic': message.topic,
          'idMessageToDelete': message._id,
          'cascade': 'cascade/'
        }).$promise.then(function(resp) {
          TatEngine.displayReturn(resp);
          message.hide = true;
          message.displayed = false;
        }, function(response) {
          TatEngine.displayReturn(response);
        });
      };

      /**
       * @ngdoc function
       * @name updateMessage
       * @methodOf TatUi.controller:messagesItem
       * @description Update a message
       */
      this.updateMessage = function(message) {
        message.updating = false;
        TatEngineMessageRsc.update({
          'topic': message.topic.substr(1),
          'idReference': message._id,
          'text': message.text,
          'action': 'update',
        }).$promise.then(function(resp) {
          message.text = resp.message.text;
        }, function(resp) {
          message.updating = true;
          TatEngine.displayReturn(resp);
        });
      };

      /**
       * @ngdoc function
       * @name hasLiked
       * @methodOf TatUi.controller:messagesItem
       * @description Define if the message is marked 'like'
       * @return {bool} If true, 'like'
       */
      this.hasLiked = function(message) {
        if (message && message.likers) {
          return _.includes(message.likers, Authentication.getIdentity().username);
        }
        return false;
      };

      /**
       * @ngdoc function
       * @name toggleLikeMessage
       * @methodOf TatUi.controller:messagesItem
       * @description toggle 'like' state on the message
       *
       */
      this.toggleLikeMessage = function(message) {
        var action = self.hasLiked(message) ? 'unlike' : 'like';
        TatEngineMessageRsc.update({
          'topic': message.topic.substr(1),
          'idReference': message._id,
          'action': action
        }).$promise.then(function(resp) {
          if (resp.message) {
            message.likers = resp.message.likers;
            message.nbLikes = resp.message.nbLikes;
          }
        }, function(err) {
          TatEngine.displayReturn(err);
        });
      };

      /**
       * @ngdoc function
       * @name removeLabel
       * @methodOf TatUi.controller:messagesItem
       * @description remove a label
       * @param {object} message Message on which to add a label
       * @param {object} label   Label {text} to remove
       */
      this.removeLabel = function(message, labelText) {
        if (!message.labels) {
          return;
        }

        TatEngineMessageRsc.update({
          'action': 'unlabel',
          'topic': message.topic.substr(1),
          'idReference': message._id,
          'text': labelText
        }).$promise.then(function(resp) {
          if (resp.message) {
            message.labels = resp.message.labels;
          }
          self.computeFlagsTask(message);
        }, function(resp) {
          TatEngine.displayReturn(resp);
        });
      };

      this.containsLabel = function(message, labelText) {
        if (message.inReplyOfIDRoot) {
          return false;
        }
        var r = false;
        if (message.labels) {
          for (var i = 0; i < message.labels.length; i++) {
            var l = message.labels[i];
            if (l.text === labelText) {
              return true;
            }
          }
        }
        return r;
      };

      this.refreshMsg = function(message) {
        message.loading = true;
        TatEngineMessagesRsc.list({
          topic: message.topic.substr(1),
          treeView: "onetree",
          idMessage: message._id,
          limit: 1,
          skip: 0
        }).$promise.then(function(data) {
          message.loading = false;
          if (!data.messages || data.messages.length != 1) {
            TatEngine.displayReturn("Invalid return while getting message");
            return
          }
          message.labels = data.messages[0].labels;
          message.tags = data.messages[0].tags;
          message.text = data.messages[0].text;
          message.nbLikes = data.messages[0].nbLikes;
          message.nbReplies = data.messages[0].nbReplies;
          message.nbVotesDown = data.messages[0].nbVotesDown;
          message.nbVotesUP = data.messages[0].nbVotesUP;
          message.dateCreation = data.messages[0].dateCreation;
          message.dateUpdate = data.messages[0].dateUpdate;
          message.replies = data.messages[0].replies;
        }, function(err) {
          message.loading = false;
          TatEngine.displayReturn(err);
        });
      }

      this.init = function(message) {
        self.refreshMsg(message);
        if ($scope.topic.topic.indexOf(self.privateTasksTopic) === 0) {
          self.isTopicTasks = true;
        }
        self.computeFlagsTask(message);
      };

      this.computeFlagsTask = function(message) {
        self.canDoneMessage = self.containsLabel(message, "doing:"+Authentication.getIdentity().username);
        self.canDeleteFromTasksMessage = self.containsLabel(message, "doing:"+Authentication.getIdentity().username);
        self.canAddToTasksMessage = !self.containsLabel(message, "doing:"+Authentication.getIdentity().username);
        if (self.containsLabel(message, "done")) {
          self.canDoneMessage = false;
        }

        if (message.topic && message.topic.indexOf("/" + self.privateTasksTopic) === 0) {
          $scope.isTopicDeletableMsg = true;
          $scope.isTopicDeletableAllMsg = true;
        }
      };

      this.init($scope.message);
    }
  };
});
<|endoftext|>


<commit_before>/**
  * MongoDB storage implementation.
  */

'use strict';

var mongodb = require('mongodb');
var BSON = mongodb.BSONPure;
var link = null;
var collection = null;
var maxResultSize = 100;

var dbConnectAndOpen = function(callback) {
  if (link) {
    callback(null, link);
  } else {
    var config = helpers.getConfig().storage;
    collection = config.collection;
    link = new mongodb.Db(
      config.db,
      new mongodb.Server(config.host, config.port, {})
    );
    link.open(callback);
  }
};

exports.dbClose = function() {
  if (link) {
    link.close();
    link = null;
  }
};

exports.insertLog = function(source, log, callback, bulk) {
  dbConnectAndOpen(function(err, db) {
    db.collection(collection, function(err, collection) {
      log.parser = source.parser;
      log.tags = source.tags;
      collection.insert(log, { safe: true }, function(err, docs) {
        // close() required after one-time insert to avoid hang
        if (!bulk) {
          exports.dbClose();
        }
        callback(err, docs);
      });
    });
  });
};

exports.getLog = function(id, callback) {
  dbConnectAndOpen(function(err, db) {
    db.collection(collection, function(err, collection) {
      collection.findOne({_id: new BSON.ObjectID(id)}, function(err, doc) {
        callback(err, doc);
        exports.dbClose();
      });
    });
  });
};

exports.getTimeline = function(params, callback) {
  dbConnectAndOpen(function(err, db) {
    db.collection(collection, function(err, collection) {
      var options = {};
      if (params.sort_attr) {
        if ('desc' == params.sort_dir) {
          options.sort = [[params.sort_attr, 'desc']];
          delete params.sort_dir;
        } else if ('asc' == params.sort_dir) {
          options.sort = [[params.sort_attr, 'asc']];
          delete params.sort_dir;
        }
        delete params.sort_attr;
      }
      if (params.limit) {
        options.limit = Math.min(parseInt(params.limit, 10), maxResultSize);
        delete params.limit;
      } else {
        options.limit = maxResultSize;
      }
      if (params.skip) {
        options.skip = parseInt(params.skip, 10);
        delete params.skip;
      }
      collection.find(params, options).toArray(function(err, data) {
        exports.dbClose();
        callback(err, data);
      });
    });
  });
};
<commit_msg>Add docs.<commit_after>/**
  * MongoDB storage implementation.
  */

'use strict';

var mongodb = require('mongodb');
var BSON = mongodb.BSONPure;
var link = null;
var collection = null;
var maxResultSize = 100;

/**
 * Connect to the DB based on config.js. Reuse a link if available.
 *
 * @param callback {Function} Fired after connection attempted.
 */
var dbConnectAndOpen = function(callback) {
  if (link) {
    callback(null, link);
  } else {
    var config = helpers.getConfig().storage;
    collection = config.collection;
    link = new mongodb.Db(
      config.db,
      new mongodb.Server(config.host, config.port, {})
    );
    link.open(callback);
  }
};

/**
 * Disconnect from the DB.
 */
exports.dbClose = function() {
  if (link) {
    link.close();
    link = null;
  }
};

/**
 * Insert a single parsed log line.
 *
 * @param source {Object} See config.js.dist for the structure.
 * @param log {Object} Output from a parser module's parse() function.
 * @param callback {Function} Fired after insert attempted.
 * @param bulk {Boolean} If true, DB connection is not auto-closed.
 */
exports.insertLog = function(source, log, callback, bulk) {
  dbConnectAndOpen(function(err, db) {
    db.collection(collection, function(err, collection) {
      log.parser = source.parser;
      log.tags = source.tags;

      collection.insert(log, { safe: true }, function(err, docs) {
        // close() required after one-time insert to avoid hang.
        if (!bulk) {
          exports.dbClose();
        }
        callback(err, docs);
      });
    });
  });
};

/**
 * Retrieve a single log's attributes.
 *
 * @param id {String} Document ID.
 * @param callback {Function} Fired after read attempted.
 */
exports.getLog = function(id, callback) {
  dbConnectAndOpen(function(err, db) {
    db.collection(collection, function(err, collection) {
      collection.findOne({_id: new BSON.ObjectID(id)}, function(err, doc) {
        callback(err, doc);
        exports.dbClose();
      });
    });
  });
};

/**
 * Retrieve the attributes of all matching logs.
 *
 * @param params {Object}
 * - sort_dir {String} 'desc' or 'asc'
 * - sort_attr {String} Ex. 'time'
 * - skip {Number} Amount of documents skipped.
 * - limit {Number} Maximum amount of documents retrieved.
 * - All other key/value pairs are considered conditions.
 * @param callback {Function} Fired after read attempted.
 */
exports.getTimeline = function(params, callback) {
  dbConnectAndOpen(function(err, db) {
    db.collection(collection, function(err, collection) {
      var options = {};
      if (params.sort_attr) {
        if ('desc' == params.sort_dir) {
          options.sort = [[params.sort_attr, 'desc']];
          delete params.sort_dir;
        } else if ('asc' == params.sort_dir) {
          options.sort = [[params.sort_attr, 'asc']];
          delete params.sort_dir;
        }
        delete params.sort_attr;
      }
      if (params.limit) {
        options.limit = Math.min(parseInt(params.limit, 10), maxResultSize);
        delete params.limit;
      } else {
        options.limit = maxResultSize;
      }
      if (params.skip) {
        options.skip = parseInt(params.skip, 10);
        delete params.skip;
      }
      collection.find(params, options).toArray(function(err, data) {
        exports.dbClose();
        callback(err, data);
      });
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

angular.module('emulvcApp')
	.directive('tier', function() {
		return {
			templateUrl: 'views/tier.html',
			restrict: 'E',
			link: function postLink(scope, element) {
				// select the needed DOM elements from the template
				var canvas = element.find('canvas');

				// var myid = scope.tier.TierName;
				scope.$watch('tierDetails', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				}, true);

				scope.$watch('vs', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
					drawTierMarkup(scope.tier, scope.vs, scope.config);
					$('.HandletiersCtrl').css('padding-top', (scope.vs.getscroll() + scope.vs.getheightOsci() + scope.vs.getheightSpectro() + (2 * $('.menu').height()) + 5) + 'px');
				}, true);

				scope.updateView = function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				};

				/**
				 * draw tier details
				 * @param tierDetails
				 * @param viewState
				 * @param cps
				 */

				function drawTierDetails(tierDetails, viewState, config) {

					if ($.isEmptyObject(tierDetails)) {
						//console.log("undef tierDetails");
						return;
					}
					if ($.isEmptyObject(viewState)) {
						//console.log("undef viewState");
						return;
					}
					if ($.isEmptyObject(config)) {
						//console.log("undef config");
						return;
					}

					var ctx = canvas[0].getContext('2d');
					ctx.clearRect(0, 0, canvas[0].width, canvas[0].height);

					//predef vars
					var sDist, posS, posE;

					sDist = viewState.getSampleDist(canvas[0].width);
					// var selection = viewState.getSelect();

					// draw name of tier
					ctx.fillStyle = config.vals.colors.labelColor;
					ctx.font = (config.vals.colors.fontPxSize + 'px' + ' ' + config.vals.colors.fontType);
					ctx.fillText(tierDetails.TierName, 5, config.vals.colors.fontPxSize);
					ctx.fillText('(' + tierDetails.type + ')', 5, config.vals.colors.fontPxSize * 2);

					var segMId = viewState.getcurMouseSegmentId();
					var segCId = viewState.getselected();
					var curID = -1;
					// var curPoS = selection[0];
					// var curPoE = selection[1];
					if (tierDetails.type === 'seg') {
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// draw segments
						var e = tierDetails.events;

						e.forEach(function(curEvt) {
							++curID;

							if (curEvt.startSample > viewState.curViewPort.sS &&
								curEvt.startSample < viewState.curViewPort.eS || //within segment
								curEvt.startSample + curEvt.sampleDur > viewState.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur < viewState.curViewPort.eS || //end in segment
								curEvt.startSample < viewState.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur > viewState.curViewPort.eS // within sample
							) {

								// draw segment start
								posS = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample));
								posE = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample + curEvt.sampleDur + 1));
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								ctx.fillRect(posS, 0, 2, canvas[0].height / 2);

								//draw segment end
								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								ctx.fillRect(posE, canvas[0].height / 2, 2, canvas[0].height);

								// draw label
								ctx.strokeStyle = config.vals.colors.labelColor;
								ctx.fillStyle = config.vals.colors.labelColor;
								var tW = ctx.measureText(curEvt.label).width;
								var tX = posS + (posE - posS) / 2 - tW / 2;
								// 			//check for enough space to stroke text
								if (posE - posS > tW) {
									ctx.fillText(curEvt.label, tX, canvas[0].height / 2 + 3);
								}

								//draw helper lines
								if (posE - posS > ctx.measureText('m').width * 3) {
									// start helper line
									ctx.strokeStyle = config.vals.colors.startBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posS, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 + 10);
									ctx.stroke();

									// draw startSample numbers
									ctx.fillStyle = config.vals.colors.startBoundaryColor;
									var sStW = ctx.measureText(curEvt.startSample).width;
									//check for enough space to stroke text
									if (posE - posS > sStW) {
										ctx.fillText(curEvt.startSample, posS + 3, canvas[0].height / 5);
									}
									// end helper line
									ctx.strokeStyle = config.vals.colors.endBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posE, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3 - 10);
									ctx.stroke();
								}
								// draw sampleDur numbers.
								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								var sDtW = ctx.measureText('dur: ' + curEvt.sampleDur).width;
								//check for enough space to stroke text
								if (posE - posS > sDtW) {
									ctx.fillText('dur: ' + curEvt.sampleDur, posE - sDtW, canvas[0].height - canvas[0].height / 12);
								}
							}
						});
					} else if (tierDetails.type === 'point') {
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// predef. vars
						var perc, tW;

						for (var k in tierDetails.events) {
							//for (curEvtNr = 0; curEvtNr < tierDetails.events.length; curEvtNr++) {
							var curEvt = tierDetails.events[k];
							// var id = viewState.getId(tierDetails, curEvt.label, curEvt.startSample);
							if (curEvt.startSample > viewState.curViewPort.sS && curEvt.startSample < viewState.curViewPort.eS) {
								perc = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample) + (sDist / 2));

								if (tierDetails.TierName === viewState.curMouseMoveTierName && segMId === viewState.curMouseMoveSegmentName) {
									console.log('this is the selected boundary');
									// 		ctx.fillStyle = config.vals.colors.selectedBoundaryColor;
									// 		ctx.fillRect(perc, 0, 8, canvas[0].height / 2 - canvas[0].height / 10);
									// 		ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 8, canvas[0].height / 2 - canvas[0].height / 10);
									// 		tW = ctx.measureText(tierDetails.events[k].label).width;
									// 		ctx.fillStyle = this.params.labelColor;
									// 		ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								} else {
									ctx.fillStyle = config.vals.colors.startBoundaryColor;
									ctx.fillRect(perc, 0, 1, canvas[0].height / 2 - canvas[0].height / 10);
									ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 1, canvas[0].height / 2 - canvas[0].height / 10);
									tW = ctx.measureText(tierDetails.events[k].label).width;
									ctx.fillStyle = config.vals.colors.labelColor;
									ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								}
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								tW = ctx.measureText(curEvt.startSample).width;
								ctx.fillText(curEvt.startSample, perc + 5, canvas[0].height / 8);

							}
						}
					}
					// draw cursor/selected area
				}

				function drawTierMarkup(tierDetails, viewState, config) {
					var ctx = canvas[1].getContext('2d');
					ctx.clearRect(0, 0, canvas[1].width, canvas[1].height);

					if (tierDetails.TierName === viewState.curClickTierName) {
						ctx.fillStyle = config.vals.colors.selectedTierColor;
						ctx.fillRect(0, 0, canvas[0].width, canvas[0].height);
					}

					var posS, posE, sDist, xOffset, curEvt;

					posS = viewState.getPos(canvas[1].width, viewState.curViewPort.selectS);
					posE = viewState.getPos(canvas[1].width, viewState.curViewPort.selectE);
					sDist = viewState.getSampleDist(canvas[1].width);

					if (posS === posE) {
						// calc. offset dependant on type of tier of mousemove  -> default is sample exact
						if (viewState.curMouseMoveTierType === 'seg') {
							xOffset = 0;
						} else {
							xOffset = (sDist / 2);
						}
						ctx.fillStyle = config.vals.colors.selectedBorderColor;
						ctx.fillRect(posS + xOffset, 0, 1, canvas[0].height);
					} else {
						ctx.fillStyle = config.vals.colors.selectedAreaColor;
						ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
						ctx.strokeStyle = config.vals.colors.selectedBoundaryColor;
						ctx.beginPath();
						ctx.moveTo(posS, 0);
						ctx.lineTo(posS, canvas[0].height);
						ctx.moveTo(posE, 0);
						ctx.lineTo(posE, canvas[0].height);
						ctx.closePath();
						ctx.stroke();

					}

					var segMId = viewState.getcurMouseSegmentId();
					var segCId = viewState.getselected();
					var tierId = viewState.getcurClickTierName();

					// draw clicked on selected areas
					if (tierId !== '' && tierDetails.TierName === tierId) {
						segCId.forEach(function(entry) {
							curEvt = tierDetails.events[entry];
							posS = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample));
							posE = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample + curEvt.sampleDur + 1));
							ctx.fillStyle = config.vals.colors.selectedSegmentColor;
							ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
							ctx.fillStyle = config.vals.colors.startBoundaryColor;
						});
					}
					// draw preselected boundary
					if (segMId !== undefined && tierDetails.TierName === viewState.getcurMouseTierName()) {
						curEvt = tierDetails.events[segMId];

						posS = Math.round(viewState.getPos(canvas[1].width, curEvt.startSample));
						posE = Math.round(viewState.getPos(canvas[1].width, curEvt.startSample + curEvt.sampleDur + 1));

						ctx.fillStyle = config.vals.colors.selectedBoundaryColor;
						ctx.fillRect(posS, 0, 3, canvas[1].height);
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
					}

				}
			}
		};
	});<commit_msg>formating...<commit_after>'use strict';

angular.module('emulvcApp')
	.directive('tier', function() {
		return {
			templateUrl: 'views/tier.html',
			restrict: 'E',
			link: function postLink(scope, element) {
				// select the needed DOM elements from the template
				var canvas = element.find('canvas');

				// var myid = scope.tier.TierName;
				scope.$watch('tierDetails', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				}, true);

				scope.$watch('vs', function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
					drawTierMarkup(scope.tier, scope.vs, scope.config);
					$('.HandletiersCtrl').css('padding-top', (scope.vs.getscroll() + scope.vs.getheightOsci() + scope.vs.getheightSpectro() + (2 * $('.menu').height()) + 5) + 'px');
				}, true);

				scope.updateView = function() {
					drawTierDetails(scope.tier, scope.vs, scope.config);
				};

				/**
				 * draw tier details
				 * @param tierDetails
				 * @param viewState
				 * @param cps
				 */

				function drawTierDetails(tierDetails, viewState, config) {

					if ($.isEmptyObject(tierDetails)) {
						//console.log("undef tierDetails");
						return;
					}
					if ($.isEmptyObject(viewState)) {
						//console.log("undef viewState");
						return;
					}
					if ($.isEmptyObject(config)) {
						//console.log("undef config");
						return;
					}

					var ctx = canvas[0].getContext('2d');
					ctx.clearRect(0, 0, canvas[0].width, canvas[0].height);

					//predef vars
					var sDist, posS, posE;

					sDist = viewState.getSampleDist(canvas[0].width);
					// var selection = viewState.getSelect();

					// draw name of tier
					ctx.fillStyle = config.vals.colors.labelColor;
					ctx.font = (config.vals.colors.fontPxSize + 'px' + ' ' + config.vals.colors.fontType);
					ctx.fillText(tierDetails.TierName, 5, config.vals.colors.fontPxSize);
					ctx.fillText('(' + tierDetails.type + ')', 5, config.vals.colors.fontPxSize * 2);

					var segMId = viewState.getcurMouseSegmentId();
					var segCId = viewState.getselected();
					var curID = -1;
					// var curPoS = selection[0];
					// var curPoE = selection[1];
					if (tierDetails.type === 'seg') {
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// draw segments
						var e = tierDetails.events;

						e.forEach(function(curEvt) {
							++curID;

							if (curEvt.startSample > viewState.curViewPort.sS &&
								curEvt.startSample < viewState.curViewPort.eS || //within segment
								curEvt.startSample + curEvt.sampleDur > viewState.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur < viewState.curViewPort.eS || //end in segment
								curEvt.startSample < viewState.curViewPort.sS &&
								curEvt.startSample + curEvt.sampleDur > viewState.curViewPort.eS // within sample
							) {

								// draw segment start
								posS = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample));
								posE = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample + curEvt.sampleDur + 1));
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								ctx.fillRect(posS, 0, 2, canvas[0].height / 2);

								//draw segment end
								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								ctx.fillRect(posE, canvas[0].height / 2, 2, canvas[0].height);

								// draw label
								ctx.strokeStyle = config.vals.colors.labelColor;
								ctx.fillStyle = config.vals.colors.labelColor;
								var tW = ctx.measureText(curEvt.label).width;
								var tX = posS + (posE - posS) / 2 - tW / 2;
								// 			//check for enough space to stroke text
								if (posE - posS > tW) {
									ctx.fillText(curEvt.label, tX, canvas[0].height / 2 + 3);
								}

								//draw helper lines
								if (posE - posS > ctx.measureText('m').width * 3) {
									// start helper line
									ctx.strokeStyle = config.vals.colors.startBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posS, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 + 10);
									ctx.stroke();

									// draw startSample numbers
									ctx.fillStyle = config.vals.colors.startBoundaryColor;
									var sStW = ctx.measureText(curEvt.startSample).width;
									//check for enough space to stroke text
									if (posE - posS > sStW) {
										ctx.fillText(curEvt.startSample, posS + 3, canvas[0].height / 5);
									}
									// end helper line
									ctx.strokeStyle = config.vals.colors.endBoundaryColor;
									ctx.beginPath();
									ctx.moveTo(posE, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3);
									ctx.lineTo(tX + tW / 2, canvas[0].height / 4 * 3 - 10);
									ctx.stroke();
								}
								// draw sampleDur numbers.
								ctx.fillStyle = config.vals.colors.endBoundaryColor;
								var sDtW = ctx.measureText('dur: ' + curEvt.sampleDur).width;
								//check for enough space to stroke text
								if (posE - posS > sDtW) {
									ctx.fillText('dur: ' + curEvt.sampleDur, posE - sDtW, canvas[0].height - canvas[0].height / 12);
								}
							}
						});
					} else if (tierDetails.type === 'point') {
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
						// predef. vars
						var perc, tW;

						for (var k in tierDetails.events) {
							//for (curEvtNr = 0; curEvtNr < tierDetails.events.length; curEvtNr++) {
							var curEvt = tierDetails.events[k];
							// var id = viewState.getId(tierDetails, curEvt.label, curEvt.startSample);
							if (curEvt.startSample > viewState.curViewPort.sS && curEvt.startSample < viewState.curViewPort.eS) {
								perc = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample) + (sDist / 2));

								if (tierDetails.TierName === viewState.curMouseMoveTierName && segMId === viewState.curMouseMoveSegmentName) {
									console.log('this is the selected boundary');
									// 		ctx.fillStyle = config.vals.colors.selectedBoundaryColor;
									// 		ctx.fillRect(perc, 0, 8, canvas[0].height / 2 - canvas[0].height / 10);
									// 		ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 8, canvas[0].height / 2 - canvas[0].height / 10);
									// 		tW = ctx.measureText(tierDetails.events[k].label).width;
									// 		ctx.fillStyle = this.params.labelColor;
									// 		ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								} else {
									ctx.fillStyle = config.vals.colors.startBoundaryColor;
									ctx.fillRect(perc, 0, 1, canvas[0].height / 2 - canvas[0].height / 10);
									ctx.fillRect(perc, canvas[0].height / 2 + canvas[0].height / 10, 1, canvas[0].height / 2 - canvas[0].height / 10);
									tW = ctx.measureText(tierDetails.events[k].label).width;
									ctx.fillStyle = config.vals.colors.labelColor;
									ctx.fillText(tierDetails.events[k].label, perc - tW / 2 + 1, canvas[0].height / 2);
								}
								ctx.fillStyle = config.vals.colors.startBoundaryColor;
								tW = ctx.measureText(curEvt.startSample).width;
								ctx.fillText(curEvt.startSample, perc + 5, canvas[0].height / 8);

							}
						}
					}
					// draw cursor/selected area
				}

				/**
				 *
				 */

				function drawTierMarkup(tierDetails, viewState, config) {
					var ctx = canvas[1].getContext('2d');
					ctx.clearRect(0, 0, canvas[1].width, canvas[1].height);

					if (tierDetails.TierName === viewState.curClickTierName) {
						ctx.fillStyle = config.vals.colors.selectedTierColor;
						ctx.fillRect(0, 0, canvas[0].width, canvas[0].height);
					}

					var posS, posE, sDist, xOffset, curEvt;

					posS = viewState.getPos(canvas[1].width, viewState.curViewPort.selectS);
					posE = viewState.getPos(canvas[1].width, viewState.curViewPort.selectE);
					sDist = viewState.getSampleDist(canvas[1].width);

					if (posS === posE) {
						// calc. offset dependant on type of tier of mousemove  -> default is sample exact
						if (viewState.curMouseMoveTierType === 'seg') {
							xOffset = 0;
						} else {
							xOffset = (sDist / 2);
						}
						ctx.fillStyle = config.vals.colors.selectedBorderColor;
						ctx.fillRect(posS + xOffset, 0, 1, canvas[0].height);
					} else {
						ctx.fillStyle = config.vals.colors.selectedAreaColor;
						ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
						ctx.strokeStyle = config.vals.colors.selectedBoundaryColor;
						ctx.beginPath();
						ctx.moveTo(posS, 0);
						ctx.lineTo(posS, canvas[0].height);
						ctx.moveTo(posE, 0);
						ctx.lineTo(posE, canvas[0].height);
						ctx.closePath();
						ctx.stroke();

					}

					var segMId = viewState.getcurMouseSegmentId();
					var segCId = viewState.getselected();
					var tierId = viewState.getcurClickTierName();

					// draw clicked on selected areas
					if (tierId !== '' && tierDetails.TierName === tierId) {
						segCId.forEach(function(entry) {
							curEvt = tierDetails.events[entry];
							posS = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample));
							posE = Math.round(viewState.getPos(canvas[0].width, curEvt.startSample + curEvt.sampleDur + 1));
							ctx.fillStyle = config.vals.colors.selectedSegmentColor;
							ctx.fillRect(posS, 0, posE - posS, canvas[0].height);
							ctx.fillStyle = config.vals.colors.startBoundaryColor;
						});
					}
					// draw preselected boundary
					if (segMId !== undefined && tierDetails.TierName === viewState.getcurMouseTierName()) {
						curEvt = tierDetails.events[segMId];

						posS = Math.round(viewState.getPos(canvas[1].width, curEvt.startSample));
						posE = Math.round(viewState.getPos(canvas[1].width, curEvt.startSample + curEvt.sampleDur + 1));

						ctx.fillStyle = config.vals.colors.selectedBoundaryColor;
						ctx.fillRect(posS, 0, 3, canvas[1].height);
						ctx.fillStyle = config.vals.colors.startBoundaryColor;
					}
				}
			}
		};
	});<|endoftext|>