<commit_before>import 'vtk.js/Sources/favicon';

import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkHttpDataSetReader from 'vtk.js/Sources/IO/Core/HttpDataSetReader';
import vtkVolume from 'vtk.js/Sources/Rendering/Core/Volume';
import vtkVolumeMapper from 'vtk.js/Sources/Rendering/Core/VolumeMapper';
import vtkInteractorStyleMPRSlice from 'vtk.js/Sources/Interaction/Style/InteractorStyleMPRSlice';

import controlPanel from './controlPanel.html';

const fullScreenRenderWindow = vtkFullScreenRenderWindow.newInstance({
  background: [0, 0, 0],
});
const renderWindow = fullScreenRenderWindow.getRenderWindow();
const renderer = fullScreenRenderWindow.getRenderer();
fullScreenRenderWindow.addController(controlPanel);

const istyle = vtkInteractorStyleMPRSlice.newInstance();
renderWindow.getInteractor().setInteractorStyle(istyle);

global.fullScreen = fullScreenRenderWindow;
global.renderWindow = renderWindow;

// ----------------------------------------------------------------------------
// Volume rendering
// ----------------------------------------------------------------------------

const actor = vtkVolume.newInstance();
const mapper = vtkVolumeMapper.newInstance();
actor.setMapper(mapper);

const reader = vtkHttpDataSetReader.newInstance({
  fetchGzip: true,
});
reader
  .setUrl(`${__BASE_PATH__}/data/volume/headsq.vti`, { loadData: true })
  .then(() => {
    const data = reader.getOutputData();

    mapper.setInputData(data);

    // set interactor style volume mapper after mapper sets input data
    istyle.setVolumeMapper(mapper);
    istyle.setSliceNormal(0, 0, 1);

    const range = istyle.getSliceRange();
    istyle.setSlice((range[0] + range[1]) / 2);

    renderer.addVolume(actor);
    renderWindow.render();
  });

// ----------------------------------------------------------------------------
// UI
// ----------------------------------------------------------------------------

function updateUI() {
  const range = istyle.getSliceRange();
  const slice = istyle.getSlice();
  const normal = istyle.getSliceNormal();

  const sliceSlider = document.querySelector('.slice');
  sliceSlider.min = range[0];
  sliceSlider.max = range[1];
  sliceSlider.value = slice;

  function toFixed(n) {
    return Number.parseFloat(n).toFixed(6);
  }

  document.querySelector('.sliceText').innerText = toFixed(slice);
  document.querySelector('.normal').innerText = normal.map(toFixed).join(', ');
  document.querySelector('.range').innerText = range.map(toFixed).join(', ');
}

document.querySelector('.slice').oninput = function onInput(ev) {
  istyle.setSlice(Number.parseFloat(ev.target.value));
  renderWindow.render();
};

istyle.onModified(updateUI);
updateUI();
<commit_msg>docs(InteractorStyleMPRSlice): fix example<commit_after>import 'vtk.js/Sources/favicon';

// use full HttpDataAccessHelper
import 'vtk.js/Sources/IO/Core/DataAccessHelper/HttpDataAccessHelper';

import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkHttpDataSetReader from 'vtk.js/Sources/IO/Core/HttpDataSetReader';
import vtkVolume from 'vtk.js/Sources/Rendering/Core/Volume';
import vtkVolumeMapper from 'vtk.js/Sources/Rendering/Core/VolumeMapper';
import vtkInteractorStyleMPRSlice from 'vtk.js/Sources/Interaction/Style/InteractorStyleMPRSlice';

import controlPanel from './controlPanel.html';

const fullScreenRenderWindow = vtkFullScreenRenderWindow.newInstance({
  background: [0, 0, 0],
});
const renderWindow = fullScreenRenderWindow.getRenderWindow();
const renderer = fullScreenRenderWindow.getRenderer();
fullScreenRenderWindow.addController(controlPanel);

const istyle = vtkInteractorStyleMPRSlice.newInstance();
renderWindow.getInteractor().setInteractorStyle(istyle);

global.fullScreen = fullScreenRenderWindow;
global.renderWindow = renderWindow;

// ----------------------------------------------------------------------------
// Volume rendering
// ----------------------------------------------------------------------------

const actor = vtkVolume.newInstance();
const mapper = vtkVolumeMapper.newInstance();
actor.setMapper(mapper);

const reader = vtkHttpDataSetReader.newInstance({
  fetchGzip: true,
});
reader
  .setUrl(`${__BASE_PATH__}/data/volume/headsq.vti`, { loadData: true })
  .then(() => {
    const data = reader.getOutputData();

    mapper.setInputData(data);

    // set interactor style volume mapper after mapper sets input data
    istyle.setVolumeMapper(mapper);
    istyle.setSliceNormal(0, 0, 1);

    const range = istyle.getSliceRange();
    istyle.setSlice((range[0] + range[1]) / 2);

    renderer.addVolume(actor);
    renderWindow.render();
  });

// ----------------------------------------------------------------------------
// UI
// ----------------------------------------------------------------------------

function updateUI() {
  const range = istyle.getSliceRange();
  const slice = istyle.getSlice();
  const normal = istyle.getSliceNormal();

  const sliceSlider = document.querySelector('.slice');
  sliceSlider.min = range[0];
  sliceSlider.max = range[1];
  sliceSlider.value = slice;

  function toFixed(n) {
    return Number.parseFloat(n).toFixed(6);
  }

  document.querySelector('.sliceText').innerText = toFixed(slice);
  document.querySelector('.normal').innerText = normal.map(toFixed).join(', ');
  document.querySelector('.range').innerText = range.map(toFixed).join(', ');
}

document.querySelector('.slice').oninput = function onInput(ev) {
  istyle.setSlice(Number.parseFloat(ev.target.value));
  renderWindow.render();
};

istyle.onModified(updateUI);
updateUI();
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import {
	ListView,
	View,
	Text,
} from 'react-native';

import css from '../../styles/css';

const dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
var scheduleData = getData();

const FullScheduleListView = ({ style, data, rows, scrollEnabled, item, card }) => {
	return (
		<ListView
			style={style}
			scrollEnabled={scrollEnabled}
			dataSource={dataSource.cloneWithRows((rows) ? (data.slice(0,rows)) : (data))}
			renderRow={(rowData, sectionID, rowID, highlightRow) => {
				<ScheduleDay
					id={rowID}
					data={rowData}
				/>
			}}
		/>
)};

var ScheduleDay = ({ id, data }) => (
	<View style={css.sc_dayContainer}>
		<Text style={css.sc_dayText}>
			{id}
		</Text>
		<DayList courseItems={data} />
	</View>
);

var DayList = ({ courseItems }) => (
	<ListView
		dataSource={dataSource.cloneWithRows(courseItems)}
		renderRow={(rowData, sectionID, rowID, highlightRow) => (
			<DayItem key={rowID} data={rowData} />
		)}
	/>
);

var DayItem = ({ data }) => (
	<View style={css.sc_dayRow}>
		<Text
			style={css.sc_courseText}
			numberOfLines={1}
		>
			{data.course_title}
		</Text>
		<Text style={css.sc_subText}>
			{data.time_string + '\n'}
			{data.building + data.room}
		</Text>
	</View>
);

FullScheduleListView.propTypes = {
	style: PropTypes.number, // Stylesheet is a number for some reason?
	data: PropTypes.array.isRequired,
	rows: PropTypes.number,
	scrollEnabled: PropTypes.bool,
	item: PropTypes.string.isRequired,
	card: PropTypes.bool,
};

FullScheduleListView.defaultProps = {
	scrollEnabled: false,
	card: false
};

export default FullScheduleListView;
<commit_msg>Add call to getData for course schedule<commit_after>import React, { PropTypes } from 'react';
import {
	ListView,
	View,
	Text,
} from 'react-native';

import css from '../../styles/css';
import { getData } from './scheduleData';

const dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
var scheduleData = getData();

const FullScheduleListView = ({ style, data, rows, scrollEnabled, item, card }) => {
	return (
		<ListView
			style={style}
			scrollEnabled={scrollEnabled}
			dataSource={dataSource.cloneWithRows((rows) ? (data.slice(0,rows)) : (data))}
			renderRow={(rowData, sectionID, rowID, highlightRow) => {
				<ScheduleDay
					id={rowID}
					data={rowData}
				/>
			}}
		/>
)};

var ScheduleDay = ({ id, data }) => (
	<View style={css.sc_dayContainer}>
		<Text style={css.sc_dayText}>
			{id}
		</Text>
		<DayList courseItems={data} />
	</View>
);

var DayList = ({ courseItems }) => (
	<ListView
		dataSource={dataSource.cloneWithRows(courseItems)}
		renderRow={(rowData, sectionID, rowID, highlightRow) => (
			<DayItem key={rowID} data={rowData} />
		)}
	/>
);

var DayItem = ({ data }) => (
	<View style={css.sc_dayRow}>
		<Text
			style={css.sc_courseText}
			numberOfLines={1}
		>
			{data.course_title}
		</Text>
		<Text style={css.sc_subText}>
			{data.time_string + '\n'}
			{data.building + data.room}
		</Text>
	</View>
);

FullScheduleListView.propTypes = {
	style: PropTypes.number, // Stylesheet is a number for some reason?
	data: PropTypes.array.isRequired,
	rows: PropTypes.number,
	scrollEnabled: PropTypes.bool,
	item: PropTypes.string.isRequired,
	card: PropTypes.bool,
};

FullScheduleListView.defaultProps = {
	scrollEnabled: false,
	card: false
};

export default FullScheduleListView;
<|endoftext|>


<commit_before>/**
 *  entry point for table
 */

$(function() {

  var Table = cdb.core.View.extend({

    el: document.body,

    events: {
      'keypress': 'keyPress',
      'keyup': 'keyUp'
    },

    initialize: function(options) {
      var self = this;
      this.user = new cdb.admin.User(this.options.user_data);

      _.bindAll(this, "noGeoRefMapMenu", "geoRefMapMenu");

      this._initModels();
      this._initViews();

      // init data
      // table change will raise the map and columns fetch

      this.table.bind('change', function() {
        self.initializated = true;
      })
      this.table.fetch()

      this.keyBind();
    },
    /**
    * Bind the keystrokes associated with menu actions
    * alt + <- : show right menu
    * alt + -> : hide right menu
    * alt + c : toggle carto
    * alt + s : toggle sql
    * @method keyBind
    * TODO: extract to a better place to allow use in all the views
    */
    keyBind: function() {
      var self = this;
      $('body').bind('keydown', function(e) {
        if(e.altKey) {
          //37 39
          if(e.keyCode == 37) { // left arrow
            e.preventDefault();
            e.stopPropagation();
            self.menu.show()
            return false;
          }
          if(e.keyCode == 39) { // right arrow
            e.preventDefault();
            e.stopPropagation();
            self.menu.hide()
            return false;
          }
          if(e.keyCode == 67) { // c key
            e.preventDefault();
            e.stopPropagation();
            self.menu.getButtonByClass('carto_mod').click(e);
            return false;
          }
          if(e.keyCode == 83) { // s key
            e.preventDefault();
            e.stopPropagation();
            self.menu.getButtonByClass('sql_mod').click(e);
            return false;
          }
        }
      });
    },

    appyQuery: function(sql) {
      var self = this;
      self.sqlView.setSQL(sql);
      self.table.useSQLView(self.sqlView);
      // if there is some error the query is rollbacked
      self.sqlView.fetch();
    },

    _initModels: function() {
      var self = this;
      this.table = new cdb.admin.CartoDBTableMetadata({
        id: this.options.table_id
      });
      this.columns = this.table.data();
      this.map = new cdb.admin.Map();
      this.infowindow = new cdb.geo.ui.InfowindowModel({
        template_name: 'table/views/infowindow_light'
      });
      this.sqlView = new cdb.admin.SQLViewData();
      this.geocoder = new cdb.admin.Geocoding('', this.table);

      //TODO: load this from an initial data file or d
      var layers = [
        {
          url: 'http://tile.stamen.com/toner/{z}/{x}/{y}.png',
          maxZoom: 17
        },
        {
          url: 'http://a.tiles.mapbox.com/v3/mapbox.mapbox-light/{z}/{x}/{y}.png',
          maxZoom: 17
        },
        //'http://tile.stamen.com/terrain/{z}/{x}/{y}.png',
        //'http://tile.stamen.com/watercolor/{z}/{x}/{y}.png',
        {
          url: 'http://a.tiles.mapbox.com/v3/mapbox.mapbox-streets/{z}/{x}/{y}.png',
          maxZoom: 17
        }

      ];

      this.baseLayers = this.user.layers;
      _(layers).map(function(m) {
        self.baseLayers.add(new cdb.admin.TileLayer({
          urlTemplate: m.url,
          read_only: true,
          maxZoom: m.maxZoom
        }));
      });

      // fetch or create map id
      this.map.relatedTo(this.table);

      this.map.bind('change:dataLayer', _.once(function() {

        // cache the value to access it in all the view
        self.dataLayer = self.map.get('dataLayer');

        // when the layer query changes the table should change
        self.dataLayer.bind('change:query', function() {
          var sql = this.get('query');
          if(sql) {
            self.appyQuery(sql);
          } else {
            self.table.useSQLView(null);
          }
        });

        // on error rollback the query in the model
        self.sqlView.bind('error', function() {
          self.dataLayer.save({query: null}, {silent: true});
        });

        // on success and no modify rows save the query!
        self.sqlView.bind('reset', function() {
          if(self.sqlView.modify_rows) {
            self.dataLayer.set({query: null}, {silent: true});
          } else {
            self.dataLayer.save(null, {silent: true});
          }
        });

        // trigger the event to ping all views
        self.dataLayer.trigger('change:query');

        var infowindowData = self.dataLayer.get('infowindow');
        if(infowindowData) {
          self.infowindow.set(infowindowData);
        } else {
          // assign a position from start
          var pos = 0;
          _(self.table.get('schema')).each(function(v) {
            self.infowindow.addField(v[0], pos);
            ++pos;
          });
        }

        // check all the fields in the infowindows are in table schema
        // remove the missing ones
        self.table.bind('change:schema', function() {
          var columns = self.table.columnNames();
          columns = _(columns).filter(function(c) {
            return !_.contains(['the_geom', 'created_at', 'updated_at'], c);
          });

          _(self.infowindow.get('fields')).each(function(c) {
            if(!_.contains(columns, c.name)) {
              self.infowindow.removeField(c.name);
            }
          });

        });

        self.infowindow.bind('change:fields change:template_name', _.debounce(function() {
          // call with silent so the layer is no realoded
          // if some view needs to be changed when infowindow is changed it should be
          // subscribed to infowindow model not to dataLayer
          // (which is only a data container for infowindow)
          self.dataLayer.save({ infowindow: self.infowindow.toJSON() }, { silent: true });
        }, 200));

      }));

    },

    _initViews: function() {
      var self = this;

      this.header = new cdb.admin.Header({
        el: this.$('header'),
        model: this.table,
        user: this.user,
        geocoder: this.geocoder
      });
      this.addView(this.header);

      this.tabs = new cdb.admin.Tabs({
        el: this.$('nav')
      });
      this.addView(this.tabs);

      this.workView = new cdb.ui.common.TabPane({
        el: this.$('.panes')
      });

      this.addView(this.workView);

      this.tableTab = new cdb.admin.TableTab({
        model: this.table,
        sqlView: this.sqlView
      });

      this.mapTab = new cdb.admin.MapTab({
        model: this.map,
        baseLayers: this.baseLayers,
        table: this.table,
        infowindow: this.infowindow
      });
      // the .click must be changed for a better way of reference the action. Ask @jsantana
      this.mapTab.bind('manual', function() { self.$('*[href="#table"]').click();})
      this.mapTab.bind('georeference', function() { self.$('.georeference').click();})

      this.globalError = new cdb.admin.GlobalError({
        el: $('.globalerror')
      });

      this.table.bind('notice', this.globalError.showError, this.globalError);

      this.addView(this.globalError);

      // used to show progress on stuff being done
      var bkg_importer = this.bkg_importer = new cdb.ui.common.BackgroundImporter({
        template_base: 'table/views/geocoder_progress',
        import_: this.geocoder
      });
      this.$el.append(this.bkg_importer.render().el);

      this.geocoder.bind('start', function() {
        self.bkg_importer.changeState(self.geocoder);
      });

      this.geocoder.bind('progress', function() {
        self.bkg_importer.render();
        if(self.geocoder.total_connections%10 == 0) {
          //self.dataLayer.trigger('change');
        }
      });

      this.geocoder.bind('finish', function() {
        self.bkg_importer.changeState(self.geocoder);
      });

      this.menu = new cdb.admin.RightMenu({});
      this.$el.append(this.menu.render().el);
      this.menu.hide();
      this.addView(this.menu);

      this.map.bind('change:dataLayer', _.once(function() {

        self.header.setDataLayer(self.dataLayer);

        self.table.bind('change:name', function() {
          self.dataLayer.set({ table_name: self.table.get('name') });
          self.dataLayer.save();
        });

        self.dataLayer.set({
          table_name: self.table.get('name'),
          user_name: self.user.get("username"),
          sql: sql,
          extra_params: {
            map_key: self.user.get('api_key')
          },
          sql_api_domain: cdb.config.get('sql_api_domain'),
          sql_api_endpoint: cdb.config.get('sql_api_endpoint'),
          sql_api_port: cdb.config.get('sql_api_port'),
          tiler_domain: cdb.config.get('tiler_domain'),
          tiler_port: cdb.config.get('tiler_port')
        });

        // set api key when we have api key and the data layer loaded
        var sql = self.table.isInSQLView() ?
                      self.table.data().getSQL() :
                      undefined;

        // lateral menu modules
        var sql = new cdb.admin.mod.SQL({
          model: self.dataLayer,
          sqlView: self.sqlView,
          table: self.table
        });

        sql.bind('writeSQL', self.appyQuery, self);

        var carto = new cdb.admin.mod.Carto({
          model: self.dataLayer,
          table: self.table
        });

        var infowindow = new cdb.admin.mod.InfoWindow({
          table: self.table,
          model: self.infowindow
        });
        self.menu.addModule(sql.render(), ['table', 'map', 'mapLite']);
        self.menu.addModule(carto.render(), 'map');
        self.menu.addModule(infowindow.render(), 'map');

        var addRow = self.menu.addToolButton('add_row', 'table');
        var addColumn = self.menu.addToolButton('add_column', 'table');
        addColumn.bind('click', function() {
            new cdb.admin.NewColumnDialog({
              table: self.table
            }).appendToBody().open();
        });
        addRow.bind('click', function() {
          self.table.data().addRow({ at: 0});
          self.trigger('createRow');
        });

      }));

      this.workView.addTab('table', this.tableTab.render());
      this.workView.addTab('map', this.mapTab.render());
      this.workView.bind('tabEnabled:map', this.mapTab.enableMap, this.mapTab);

      this.workView.bind('tabEnabled', this.tabs.activate);
      this.workView.active('table');

      // global click
      enableClickOut(this.$el);

      this.mapTab.bind('missingClick', function() {
        self.menu.hide();
      });
      this.tableTab.tableView.bind('cellClick', function() {
        self.menu.hide();
      });

      this.mapTab.bind('noGeoRef', this.noGeoRefMapMenu);
      this.mapTab.bind('geoRef', this.geoRefMapMenu)

      // On resize window...
      $(window).bind("resize", this._onResize);

    },

    // Close all dialogs in window resize
    _onResize: function(e) {
      cdb.god.trigger("closeDialogs");
    },

    keyUp: function(e) {
    },

    keyPress: function(e) {
      /*if(e.which == 19) {
        this.menu.show();
        this.menu.active('sql_mod');
        e.preventDefault();
        return false;
      }*/
    },

    noGeoRefMapMenu: function(e) {
      this.menu.hideMapTools();
    },

    geoRefMapMenu: function(e) {
      this.menu.showMapTools();
    }

  });

    cdb._test = cdb._test || {};
    cdb._test.Table = Table;

    var TableRouter = Backbone.Router.extend({

        initialize: function(table) {
          var self = this;
          this.table = table;
          /*
          this.table.table.bind('change:dataSource', function() {
            if(this.isInSQLView()) {
              var sql = this.data().getSQL();
              if(!this.alterTableData(sql)) {
                self.navigate('table/' + encodeURIComponent(sql));
              }
            } else {
              self.navigate('table');
            }
          });
          */
        },

        routes: {
            '': 'index',
            'table': 'index',
            'table/:sql': 'table_sql',
            'map': 'map'
        },

        index: function() {
          this.table.workView.active('table');
          this.table.menu.showTools('table');
        },

        table_sql: function(sql) {
          this.index();
          if(!this.table.table.alterTableData(sql)) {
            this.table.sqlView.setSQL(decodeURIComponent(sql));
            this.table.table.useSQLView(this.table.sqlView);
          }
        },

        map: function() {
          this.table.workView.active('map');
          window.a = this.table;
          if(!this.table.menu.hiddenMapTools) {
            this.table.menu.showTools('map');
          } else {
            this.table.menu.showTools('mapLite');
          }
        }

    });

    cdb.init(function() {
      cdb.config.set(config);
      cdb.templates.namespace = 'cartodb/';

      var table = new Table({
        table_id: table_id,
        user_data: user_data
      });
      window.table = table;
      if(table.initializated) {
        var router = new TableRouter(window.table);
        // expose to debug
        Backbone.history.start();
      } else {
        table.table.bind('change', function() {
          var router = new TableRouter(window.table);
          // expose to debug
          Backbone.history.start();
        })
      }
    });

});
<commit_msg>cleaning the mess I made (the bound method was being called more than once and that was breaking the backbone history)<commit_after>/**
 *  entry point for table
 */

$(function() {

  var Table = cdb.core.View.extend({

    el: document.body,

    events: {
      'keypress': 'keyPress',
      'keyup': 'keyUp'
    },

    initialize: function(options) {
      var self = this;
      this.user = new cdb.admin.User(this.options.user_data);

      _.bindAll(this, "noGeoRefMapMenu", "geoRefMapMenu");

      this._initModels();
      this._initViews();

      // init data
      // table change will raise the map and columns fetch

      this.table.bind('change', function() {
        self.initializated = true;
      })
      this.table.fetch()

      this.keyBind();
    },
    /**
    * Bind the keystrokes associated with menu actions
    * alt + <- : show right menu
    * alt + -> : hide right menu
    * alt + c : toggle carto
    * alt + s : toggle sql
    * @method keyBind
    * TODO: extract to a better place to allow use in all the views
    */
    keyBind: function() {
      var self = this;
      $('body').bind('keydown', function(e) {
        if(e.altKey) {
          //37 39
          if(e.keyCode == 37) { // left arrow
            e.preventDefault();
            e.stopPropagation();
            self.menu.show()
            return false;
          }
          if(e.keyCode == 39) { // right arrow
            e.preventDefault();
            e.stopPropagation();
            self.menu.hide()
            return false;
          }
          if(e.keyCode == 67) { // c key
            e.preventDefault();
            e.stopPropagation();
            self.menu.getButtonByClass('carto_mod').click(e);
            return false;
          }
          if(e.keyCode == 83) { // s key
            e.preventDefault();
            e.stopPropagation();
            self.menu.getButtonByClass('sql_mod').click(e);
            return false;
          }
        }
      });
    },

    appyQuery: function(sql) {
      var self = this;
      self.sqlView.setSQL(sql);
      self.table.useSQLView(self.sqlView);
      // if there is some error the query is rollbacked
      self.sqlView.fetch();
    },

    _initModels: function() {
      var self = this;
      this.table = new cdb.admin.CartoDBTableMetadata({
        id: this.options.table_id
      });
      this.columns = this.table.data();
      this.map = new cdb.admin.Map();
      this.infowindow = new cdb.geo.ui.InfowindowModel({
        template_name: 'table/views/infowindow_light'
      });
      this.sqlView = new cdb.admin.SQLViewData();
      this.geocoder = new cdb.admin.Geocoding('', this.table);

      //TODO: load this from an initial data file or d
      var layers = [
        {
          url: 'http://tile.stamen.com/toner/{z}/{x}/{y}.png',
          maxZoom: 17
        },
        {
          url: 'http://a.tiles.mapbox.com/v3/mapbox.mapbox-light/{z}/{x}/{y}.png',
          maxZoom: 17
        },
        //'http://tile.stamen.com/terrain/{z}/{x}/{y}.png',
        //'http://tile.stamen.com/watercolor/{z}/{x}/{y}.png',
        {
          url: 'http://a.tiles.mapbox.com/v3/mapbox.mapbox-streets/{z}/{x}/{y}.png',
          maxZoom: 17
        }

      ];

      this.baseLayers = this.user.layers;
      _(layers).map(function(m) {
        self.baseLayers.add(new cdb.admin.TileLayer({
          urlTemplate: m.url,
          read_only: true,
          maxZoom: m.maxZoom
        }));
      });

      // fetch or create map id
      this.map.relatedTo(this.table);

      this.map.bind('change:dataLayer', _.once(function() {

        // cache the value to access it in all the view
        self.dataLayer = self.map.get('dataLayer');

        // when the layer query changes the table should change
        self.dataLayer.bind('change:query', function() {
          var sql = this.get('query');
          if(sql) {
            self.appyQuery(sql);
          } else {
            self.table.useSQLView(null);
          }
        });

        // on error rollback the query in the model
        self.sqlView.bind('error', function() {
          self.dataLayer.save({query: null}, {silent: true});
        });

        // on success and no modify rows save the query!
        self.sqlView.bind('reset', function() {
          if(self.sqlView.modify_rows) {
            self.dataLayer.set({query: null}, {silent: true});
          } else {
            self.dataLayer.save(null, {silent: true});
          }
        });

        // trigger the event to ping all views
        self.dataLayer.trigger('change:query');

        var infowindowData = self.dataLayer.get('infowindow');
        if(infowindowData) {
          self.infowindow.set(infowindowData);
        } else {
          // assign a position from start
          var pos = 0;
          _(self.table.get('schema')).each(function(v) {
            self.infowindow.addField(v[0], pos);
            ++pos;
          });
        }

        // check all the fields in the infowindows are in table schema
        // remove the missing ones
        self.table.bind('change:schema', function() {
          var columns = self.table.columnNames();
          columns = _(columns).filter(function(c) {
            return !_.contains(['the_geom', 'created_at', 'updated_at'], c);
          });

          _(self.infowindow.get('fields')).each(function(c) {
            if(!_.contains(columns, c.name)) {
              self.infowindow.removeField(c.name);
            }
          });

        });

        self.infowindow.bind('change:fields change:template_name', _.debounce(function() {
          // call with silent so the layer is no realoded
          // if some view needs to be changed when infowindow is changed it should be
          // subscribed to infowindow model not to dataLayer
          // (which is only a data container for infowindow)
          self.dataLayer.save({ infowindow: self.infowindow.toJSON() }, { silent: true });
        }, 200));

      }));

    },

    _initViews: function() {
      var self = this;

      this.header = new cdb.admin.Header({
        el: this.$('header'),
        model: this.table,
        user: this.user,
        geocoder: this.geocoder
      });
      this.addView(this.header);

      this.tabs = new cdb.admin.Tabs({
        el: this.$('nav')
      });
      this.addView(this.tabs);

      this.workView = new cdb.ui.common.TabPane({
        el: this.$('.panes')
      });

      this.addView(this.workView);

      this.tableTab = new cdb.admin.TableTab({
        model: this.table,
        sqlView: this.sqlView
      });

      this.mapTab = new cdb.admin.MapTab({
        model: this.map,
        baseLayers: this.baseLayers,
        table: this.table,
        infowindow: this.infowindow
      });
      // the .click must be changed for a better way of reference the action. Ask @jsantana
      this.mapTab.bind('manual', function() { self.$('*[href="#table"]').click();})
      this.mapTab.bind('georeference', function() { self.$('.georeference').click();})

      this.globalError = new cdb.admin.GlobalError({
        el: $('.globalerror')
      });

      this.table.bind('notice', this.globalError.showError, this.globalError);

      this.addView(this.globalError);

      // used to show progress on stuff being done
      var bkg_importer = this.bkg_importer = new cdb.ui.common.BackgroundImporter({
        template_base: 'table/views/geocoder_progress',
        import_: this.geocoder
      });
      this.$el.append(this.bkg_importer.render().el);

      this.geocoder.bind('start', function() {
        self.bkg_importer.changeState(self.geocoder);
      });

      this.geocoder.bind('progress', function() {
        self.bkg_importer.render();
        if(self.geocoder.total_connections%10 == 0) {
          //self.dataLayer.trigger('change');
        }
      });

      this.geocoder.bind('finish', function() {
        self.bkg_importer.changeState(self.geocoder);
      });

      this.menu = new cdb.admin.RightMenu({});
      this.$el.append(this.menu.render().el);
      this.menu.hide();
      this.addView(this.menu);

      this.map.bind('change:dataLayer', _.once(function() {

        self.header.setDataLayer(self.dataLayer);

        self.table.bind('change:name', function() {
          self.dataLayer.set({ table_name: self.table.get('name') });
          self.dataLayer.save();
        });

        self.dataLayer.set({
          table_name: self.table.get('name'),
          user_name: self.user.get("username"),
          sql: sql,
          extra_params: {
            map_key: self.user.get('api_key')
          },
          sql_api_domain: cdb.config.get('sql_api_domain'),
          sql_api_endpoint: cdb.config.get('sql_api_endpoint'),
          sql_api_port: cdb.config.get('sql_api_port'),
          tiler_domain: cdb.config.get('tiler_domain'),
          tiler_port: cdb.config.get('tiler_port')
        });

        // set api key when we have api key and the data layer loaded
        var sql = self.table.isInSQLView() ?
                      self.table.data().getSQL() :
                      undefined;

        // lateral menu modules
        var sql = new cdb.admin.mod.SQL({
          model: self.dataLayer,
          sqlView: self.sqlView,
          table: self.table
        });

        sql.bind('writeSQL', self.appyQuery, self);

        var carto = new cdb.admin.mod.Carto({
          model: self.dataLayer,
          table: self.table
        });

        var infowindow = new cdb.admin.mod.InfoWindow({
          table: self.table,
          model: self.infowindow
        });
        self.menu.addModule(sql.render(), ['table', 'map', 'mapLite']);
        self.menu.addModule(carto.render(), 'map');
        self.menu.addModule(infowindow.render(), 'map');

        var addRow = self.menu.addToolButton('add_row', 'table');
        var addColumn = self.menu.addToolButton('add_column', 'table');
        addColumn.bind('click', function() {
            new cdb.admin.NewColumnDialog({
              table: self.table
            }).appendToBody().open();
        });
        addRow.bind('click', function() {
          self.table.data().addRow({ at: 0});
          self.trigger('createRow');
        });

      }));

      this.workView.addTab('table', this.tableTab.render());
      this.workView.addTab('map', this.mapTab.render());
      this.workView.bind('tabEnabled:map', this.mapTab.enableMap, this.mapTab);

      this.workView.bind('tabEnabled', this.tabs.activate);
      this.workView.active('table');

      // global click
      enableClickOut(this.$el);

      this.mapTab.bind('missingClick', function() {
        self.menu.hide();
      });
      this.tableTab.tableView.bind('cellClick', function() {
        self.menu.hide();
      });

      this.mapTab.bind('noGeoRef', this.noGeoRefMapMenu);
      this.mapTab.bind('geoRef', this.geoRefMapMenu)

      // On resize window...
      $(window).bind("resize", this._onResize);

    },

    // Close all dialogs in window resize
    _onResize: function(e) {
      cdb.god.trigger("closeDialogs");
    },

    keyUp: function(e) {
    },

    keyPress: function(e) {
      /*if(e.which == 19) {
        this.menu.show();
        this.menu.active('sql_mod');
        e.preventDefault();
        return false;
      }*/
    },

    noGeoRefMapMenu: function(e) {
      this.menu.hideMapTools();
    },

    geoRefMapMenu: function(e) {
      this.menu.showMapTools();
    }

  });

    cdb._test = cdb._test || {};
    cdb._test.Table = Table;

    var TableRouter = Backbone.Router.extend({

        initialize: function(table) {
          var self = this;
          this.table = table;
          /*
          this.table.table.bind('change:dataSource', function() {
            if(this.isInSQLView()) {
              var sql = this.data().getSQL();
              if(!this.alterTableData(sql)) {
                self.navigate('table/' + encodeURIComponent(sql));
              }
            } else {
              self.navigate('table');
            }
          });
          */
        },

        routes: {
            '': 'index',
            'table': 'index',
            'table/:sql': 'table_sql',
            'map': 'map'
        },

        index: function() {
          this.table.workView.active('table');
          this.table.menu.showTools('table');
        },

        table_sql: function(sql) {
          this.index();
          if(!this.table.table.alterTableData(sql)) {
            this.table.sqlView.setSQL(decodeURIComponent(sql));
            this.table.table.useSQLView(this.table.sqlView);
          }
        },

        map: function() {
          this.table.workView.active('map');
          window.a = this.table;
          if(!this.table.menu.hiddenMapTools) {
            this.table.menu.showTools('map');
          } else {
            this.table.menu.showTools('mapLite');
          }
        }

    });

    cdb.init(function() {
      cdb.config.set(config);
      cdb.templates.namespace = 'cartodb/';

      var table = new Table({
        table_id: table_id,
        user_data: user_data
      });
      window.table = table;
      if(table.initializated) {
        var router = new TableRouter(window.table);
        // expose to debug
        Backbone.history.start();
      } else {
        table.table.bind('change', _.once(function() {
          var router = new TableRouter(window.table);
          // expose to debug
          Backbone.history.start();
        }))
      }
    });

});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/cipmankVychodni/01.jpg'),
  require('../../images/animals/cipmankVychodni/02.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/cipmankVychodni/01-thumb.jpg'),
  require('../../images/animals/cipmankVychodni/02-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
        <AnimalText>
        Zdravíme vás, kamarádi a milovníci zvířátek! Jmenujeme se čipmankové východní a do Brna jsme přicestovali v roce 2014. Milí chovatelé ze zdejší zoo nás s nadšením přivítali a darovali nám tento útulný domov u pavilonu orlů. Ve volné přírodě na nás sice v České republice nenarazíte, ale pokud rádi sledujete pohádky, tak jste o čipmancích jistě už slyšeli. Děti z celého světa nás znají jako Chipa a Dalea z Rychlé roty a proslavili jsme se i jako nadané zpívající veverky z filmu Alvin a chipmunkové. Náš skutečný život je ale ještě zajímavější, a pokud chcete zjistit víc, pozorně čtěte dál.
        </AnimalText>
        <AnimalText>
        Naši čipernou partu tvoří celkem dva samečci a dvě samičky. Měli byste o nás ale vědět, že jsme samotáři a moc času ve společnosti kamarádů netrávíme. V naší expozici tak většinou zahlédnete pouze jeden čipmančí pár. Tušíte, proč nám říkají čipmankové východní? Pocházíme totiž ze světlých lesů na východě Ameriky a Kanady. Jsme zemní veverky, což znamená, že nebydlíme na stromech, ale hloubíme si podzemní nory plné spletitých chodbiček. Dorůstáme o něco menší délky než běžná veverka obecná, kterou určitě znáte. Rádi šplháme i po větvích, ale rozhodně od nás nečekejte žádné akrobatické skoky mezi stromy, jak to rády předvádějí stromové veverky. My spíš jen hbitě pobíháme, zejména když zrají oříšky, žaludy, semínka nebo ovoce, to je potom dobrota! Potravu sbíráme i na zemi a plníme nejen svá bříška, ale i lícní vaky (říká se jim také torby). V nich si jídlo přenášíme do nory, abychom měli zásoby na zimu, kterou většinou celou prospíme. (Páni zoologové tomu říkají hibernace.) Na jaro pak přivádíme na svět potomky (většinou 4–5 mláďat).
        </AnimalText>
        <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
        Nezapomeňte si také všimnout našeho půvabného sametového kožíšku a huňatého ocásku. Srst míváme šedou nebo rezavě hnědou a naším hlavním znakem jsou světlé a tmavé pruhy, které se nám střídají po obou stranách těla a v obličeji. Vyfotit nás není vůbec jednoduché, však si to zkuste, nejspíš vám na fotce zůstane jen rozmazaná šmouha. Rychlá rota nám v televizi neříkali náhodou, jsme opravdoví neposedové. Jestliže nás nevidíte, nejspíš se schováváme v norách nebo mezi větvemi. V tom případě pozorně sledujte naši expozici, a pokud nejsme zrovna uložení k zimnímu spánku, určitě se vám ukážeme.
        </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;
<commit_msg>Update cipmankVychodni.child.js<commit_after>import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/cipmankVychodni/01.jpg'),
  require('../../images/animals/cipmankVychodni/02.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/cipmankVychodni/01-thumb.jpg'),
  require('../../images/animals/cipmankVychodni/02-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
        <AnimalText>
        Zdravíme vás, kamarádi a milovníci zvířátek! Jmenujeme se čipmankové východní a do Brna jsme přicestovali v roce 2014. Milí chovatelé ze zdejší zoo nás s nadšením přivítali a darovali nám tento útulný domov u voliéry orlů. Ve volné přírodě na nás sice v České republice nenarazíte, ale pokud rádi sledujete pohádky, tak jste o čipmancích jistě už slyšeli. Děti z celého světa nás znají jako Chipa a Dalea z Rychlé roty a proslavili jsme se i jako nadané zpívající veverky z filmu Alvin a chipmunkové. Náš skutečný život je ale ještě zajímavější, a pokud chcete zjistit víc, pozorně čtěte dál.
        </AnimalText>
        <AnimalText>
        Naši čipernou partu tvoří celkem dva samečci a dvě samičky. Měli byste o nás ale vědět, že jsme samotáři a moc času ve společnosti kamarádů netrávíme. V naší expozici tak většinou zahlédnete pouze jeden čipmančí pár. Tušíte, proč nám říkají čipmankové východní? Pocházíme totiž ze světlých lesů na východě Spojených států amerických a Kanady. Jsme zemní veverky, což znamená, že nebydlíme na stromech, ale hloubíme si podzemní nory plné spletitých chodbiček. Dorůstáme o něco menší délky než běžná veverka obecná, kterou určitě znáte. Rádi šplháme i po větvích, ale rozhodně od nás nečekejte žádné akrobatické skoky mezi stromy, jak to rády předvádějí stromové veverky. My spíš jen hbitě pobíháme, zejména když zrají oříšky, žaludy, semínka nebo ovoce, to je potom dobrota! Potravu sbíráme i na zemi a plníme nejen svá bříška, ale i lícní vaky (říká se jim také torby). V nich si jídlo přenášíme do nory, abychom měli zásoby na zimu, kterou většinou celou prospíme. (Páni zoologové tomu říkají hibernace.) Na jaro pak přivádíme na svět potomky (většinou 4–5 mláďat).
        </AnimalText>
        <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
        Nezapomeňte si také všimnout našeho půvabného sametového kožíšku a huňatého ocásku. Srst míváme šedou nebo rezavě hnědou a naším hlavním znakem jsou světlé a tmavé pruhy, které se nám střídají po obou stranách těla a v obličeji. Vyfotit nás není vůbec jednoduché, však si to zkuste, nejspíš vám na fotce zůstane jen rozmazaná šmouha. Rychlá rota nám v televizi neříkali náhodou, jsme opravdoví neposedové. Jestliže nás nevidíte, nejspíš se schováváme v norách nebo mezi větvemi. V tom případě pozorně sledujte naši expozici, a pokud nejsme zrovna uložení k zimnímu spánku, určitě se vám ukážeme.
        </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;
<|endoftext|>


<commit_before>var init = function () {
    "use strict";

    var
        select = null
        ,caption = null
        ,captionText = null
        ,options = null
        ,searchBox = null
        ,searchTextBox = null
        ,list = null
    ;

    $('.custom-select').each(function () {
        select = $(this).find('select')

        caption = $('

');
        captionText = $('

');
        options = $('

');
        searchBox = $('

');
        searchTextBox = $('<input></input>');
        list = $('

');

        // select.hide();

        searchBox.addClass('search-box');
        caption.addClass('caption retracted');
        captionText.addClass('text');
        options.addClass('options-box');
        list.addClass('select');

        searchTextBox.attr('type', 'text');

        $(this).append(caption);
        caption.append(captionText);
        $(this).append(options);
        options.append(searchBox);
        searchBox.append(searchTextBox);
        options.append(list);

        buildOpts();

        setActionToSelect();
    });

    // toggle
    $('.custom-select .caption').on('click', function () {
        $(this).parent().find('.options-box').toggle();
        toggleCaptionClass();
    });

    // find and build options
    var
        inputText = null
        ,wrapper = null
        ,foundsList = null
        ,foundsOptions = null
        ,optText = null
        ,searchIndex = null
        ,prevSliceTextNoSearch = null
        ,sliceFound = null
        ,remainderSliceTextNoSearch = null
        ,newOpt = null
        ,spanSliceFound = null
    ;
    $('.custom-select input[type=text]').on('keyup', function (e) {
        inputText = $(this);
        wrapper = inputText.closest('.custom-select');
        options = wrapper.find('ul.select li')

        // cria a lista das opções e a caixa de texto, dinamicamente, e apenas após a pesquisa. Caso ela já tenha sido criada, ela não é recriada, ela é apenas limpada.
        if(wrapper.find('ul.founds-list').length === 0) {
            foundsList = $('

').addClass('founds-list');
            foundsList.insertAfter( wrapper.find('.search-box') );
        } else {
            foundsList.empty();
        }

        foundsOptions = foundsList.find('li');

        if(inputText.val() !== '') {

            options.each(function (i, option) {

                optText = option.textContent.trim();
                searchIndex = optText.toLowerCase().search( inputText.val().toLowerCase() );
                if(searchIndex > -1) {
                    foundsList.show();
                    options.parent().hide();

                    prevSliceTextNoSearch = optText.slice(0, searchIndex);

                    sliceFound = optText.slice(prevSliceTextNoSearch.length, prevSliceTextNoSearch.length + inputText.val().length);

                    remainderSliceTextNoSearch = optText.slice(prevSliceTextNoSearch.length + sliceFound.length, optText.length);

                    newOpt = $('

');
                    spanSliceFound = $('');

                    newOpt.append(prevSliceTextNoSearch);
                    newOpt.append(spanSliceFound);
                    spanSliceFound.addClass('slice-found');
                    spanSliceFound.text(sliceFound);
                    newOpt.append(remainderSliceTextNoSearch);
                    newOpt.attr( 'data-value', $(option).data('value') );

                    foundsList.prepend(newOpt);
                }

            });

            setActionToSelect();

        } else {
            options.parent().show();
            foundsList.hide();
        }
    });

}

jQuery.fn.build = function () {

    var
        selects = $(this)
        ,caption = null
        ,captionText = null
        ,listBox = null
        ,searchBox = null
        ,searchTextBox = null
        ,list = null
        ,select = null
        ,wrapper = null
    ;

    selects.each(function (i, select) {
        select = $(select);
        select.hide();
        wrapper = $('

');
        wrapper.addClass('custom-select');
        select.parent().append(wrapper);
        wrapper.append(select);

        caption = $('

');
        captionText = $('

');
        listBox = $('

');
        // searchBox = $('

');
        // searchTextBox = $('<input></input>');
        list = $('

');

        // searchBox.addClass('search-box');
        caption.addClass('caption retracted');
        captionText.addClass('text');
        listBox.addClass('options-box');
        list.addClass('select');

        // searchTextBox.attr('type', 'text');

        wrapper.append(caption);
        caption.append(captionText);
        wrapper.append(listBox);
        // listBox.append(searchBox);
        // searchBox.append(searchTextBox);
        listBox.append(list);

        buildOpts(list);

        // toggle
        caption.on('click', function () {
            listBox.toggle();
            toggleCaptionClass(caption);
        });

        setActionToSelect(list);
    });
    //pegar o pai do select, criar o custom-select, por causa do css

}

var buildOpts = function (jqObj) {
    "use strict";

    var
        wrapper = jqObj.closest('.custom-select')
        ,select = wrapper.find('select')
        ,list = wrapper.find('ul.select')
        ,options = select.find('option')
        ,captionText = wrapper.find('.caption .text')
        ,option = null
        ,li = null
    ;

    options.each(function (i, tag) {
        option = $(tag);
        li = $('

');

        li.attr( 'data-value', option.attr('value') );
        li.text( option.text() );
        list.append(li);

        if( option.attr('selected') ) {
            captionText.text( option.text() );
        }
    });

}

var toggleCaptionClass = function (jqObj) {
    "use strict";
    jqObj.toggleClass('expanded', 'retracted');
}

// click out
$(document).click(function (e) {

    var
        wrapper = $('.custom-select')
        ,optionsBoxes = wrapper.find('.options-box')
        captions = wrapper.find('.caption');
    ;

    if( $(e.target).closest('.custom-select').length === 0 ) {

        if( optionsBoxes.is(':visible') ) {
            optionsBoxes.hide();
            captions.removeClass('expanded');
        }

    }

});

//select onclick
var setActionToSelect = function (jqObj) {
    "use strict";

    jqObj.find('li').on('click', function () {
        var
            wrapper = jqObj.closest('.custom-select')
            ,caption = wrapper.find('.caption')
            ,value = $(this).data('value')
            ,select = wrapper.find('select')
            ,captionText = wrapper.find('.caption .text')
            ,selected = null
        ;

        // remove selection
        select.find('option:selected').attr('selected', false);

        // select
        selected = select.find('option[value="' + value + '"]');
        selected.attr('selected', true);

        captionText.text( selected.text() );

        // esconde opções
        wrapper.find('.options-box').hide();

        toggleCaptionClass(caption);
    });
}

// $(function () {
//     'use strict';

//     if( $('.custom-select').length > 0 ) {
//         init();
//     }

// });
<commit_msg>ajusta bug<commit_after>var init = function () {
    "use strict";

    var
        select = null
        ,caption = null
        ,captionText = null
        ,options = null
        ,searchBox = null
        ,searchTextBox = null
        ,list = null
    ;

    $('.custom-select').each(function () {
        select = $(this).find('select')

        caption = $('

');
        captionText = $('

');
        options = $('

');
        searchBox = $('

');
        searchTextBox = $('<input></input>');
        list = $('

');

        // select.hide();

        searchBox.addClass('search-box');
        caption.addClass('caption retracted');
        captionText.addClass('text');
        options.addClass('options-box');
        list.addClass('select');

        searchTextBox.attr('type', 'text');

        $(this).append(caption);
        caption.append(captionText);
        $(this).append(options);
        options.append(searchBox);
        searchBox.append(searchTextBox);
        options.append(list);

        buildOpts();

        setActionToSelect();
    });

    // toggle
    caption.on('click', function () {
        $(this).parent().find('.options-box').toggle();
        toggleCaptionClass();
    });

    // find and build options
    var
        inputText = null
        ,wrapper = null
        ,foundsList = null
        ,foundsOptions = null
        ,optText = null
        ,searchIndex = null
        ,prevSliceTextNoSearch = null
        ,sliceFound = null
        ,remainderSliceTextNoSearch = null
        ,newOpt = null
        ,spanSliceFound = null
    ;
    $('.custom-select input[type=text]').on('keyup', function (e) {
        inputText = $(this);
        wrapper = inputText.closest('.custom-select');
        options = wrapper.find('ul.select li')

        // cria a lista das opções e a caixa de texto, dinamicamente, e apenas após a pesquisa. Caso ela já tenha sido criada, ela não é recriada, ela é apenas limpada.
        if(wrapper.find('ul.founds-list').length === 0) {
            foundsList = $('

').addClass('founds-list');
            foundsList.insertAfter( wrapper.find('.search-box') );
        } else {
            foundsList.empty();
        }

        foundsOptions = foundsList.find('li');

        if(inputText.val() !== '') {

            options.each(function (i, option) {

                optText = option.textContent.trim();
                searchIndex = optText.toLowerCase().search( inputText.val().toLowerCase() );
                if(searchIndex > -1) {
                    foundsList.show();
                    options.parent().hide();

                    prevSliceTextNoSearch = optText.slice(0, searchIndex);

                    sliceFound = optText.slice(prevSliceTextNoSearch.length, prevSliceTextNoSearch.length + inputText.val().length);

                    remainderSliceTextNoSearch = optText.slice(prevSliceTextNoSearch.length + sliceFound.length, optText.length);

                    newOpt = $('

');
                    spanSliceFound = $('');

                    newOpt.append(prevSliceTextNoSearch);
                    newOpt.append(spanSliceFound);
                    spanSliceFound.addClass('slice-found');
                    spanSliceFound.text(sliceFound);
                    newOpt.append(remainderSliceTextNoSearch);
                    newOpt.attr( 'data-value', $(option).data('value') );

                    foundsList.prepend(newOpt);
                }

            });

            setActionToSelect();

        } else {
            options.parent().show();
            foundsList.hide();
        }
    });

}

jQuery.fn.build = function () {

    var
        selects = $(this)
        ,caption = null
        ,captionText = null
        ,listBox = null
        ,searchBox = null
        ,searchTextBox = null
        ,list = null
        ,select = null
        ,wrapper = null
    ;

    selects.each(function (i, select) {
        select = $(select);
        select.hide();
        wrapper = $('

');
        wrapper.addClass('custom-select');
        select.parent().append(wrapper);
        wrapper.append(select);

        caption = $('

');
        captionText = $('

');
        listBox = $('

');
        // searchBox = $('

');
        // searchTextBox = $('<input></input>');
        list = $('

');

        // searchBox.addClass('search-box');
        caption.addClass('caption retracted');
        captionText.addClass('text');
        listBox.addClass('options-box');
        list.addClass('select');

        // searchTextBox.attr('type', 'text');

        wrapper.append(caption);
        caption.append(captionText);
        wrapper.append(listBox);
        // listBox.append(searchBox);
        // searchBox.append(searchTextBox);
        listBox.append(list);

        buildOpts(list);

        // toggle
        caption.on('click', function () {
            wrapper = $(this).closest('.custom-select');
            wrapper.find('.options-box').toggle();
            toggleCaptionClass( $(this) );
        });

        setActionToSelect(list);
    });

}

var buildOpts = function (jqObj) {
    "use strict";

    var
        wrapper = jqObj.closest('.custom-select')
        ,select = wrapper.find('select')
        ,list = wrapper.find('ul.select')
        ,options = select.find('option')
        ,captionText = wrapper.find('.caption .text')
        ,option = null
        ,li = null
    ;

    options.each(function (i, tag) {
        option = $(tag);
        li = $('

');

        li.attr( 'data-value', option.attr('value') );
        li.text( option.text() );
        list.append(li);

        if( option.attr('selected') ) {
            captionText.text( option.text() );
        }
    });

}

var toggleCaptionClass = function (jqObj) {
    "use strict";
    jqObj.toggleClass('expanded', 'retracted');
}

// click out
$(document).click(function (e) {

    var
        wrapper = $('.custom-select')
        ,optionsBoxes = wrapper.find('.options-box')
        captions = wrapper.find('.caption');
    ;

    if( $(e.target).closest('.custom-select').length === 0 ) {

        if( optionsBoxes.is(':visible') ) {
            optionsBoxes.hide();
            captions.removeClass('expanded');
        }

    }

});

//select onclick
var setActionToSelect = function (jqObj) {
    "use strict";

    jqObj.find('li').on('click', function () {
        var
            wrapper = jqObj.closest('.custom-select')
            ,caption = wrapper.find('.caption')
            ,value = $(this).data('value')
            ,select = wrapper.find('select')
            ,captionText = wrapper.find('.caption .text')
            ,selected = null
        ;

        // remove selection
        select.find('option:selected').attr('selected', false);

        // select
        selected = select.find('option[value="' + value + '"]');
        selected.attr('selected', true);

        captionText.text( selected.text() );

        // esconde opções
        wrapper.find('.options-box').hide();

        toggleCaptionClass(caption);
    });
}

// $(function () {
//     'use strict';

//     if( $('.custom-select').length > 0 ) {
//         init();
//     }

// });
<|endoftext|>


<commit_before>/*
  This file is part of Booktype.
  Copyright (c) 2013 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>

  Booktype 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.

  Booktype 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 Booktype.  If not, see <http://www.gnu.org/licenses/>.
*/

(function(win, jquery, _) {

	jquery.namespace('win.booktype.editor.edit');

  win.booktype.editor.edit = function() {
      var chapterID = null;
      var tabs = [];

      var _fixFootnotes = function() {
        jquery('#content #footnotes OL').empty();

        _.each(jquery('sup.footnote', jquery('#contenteditor')), function(item, n) {
          var $foot = jquery(item);
          var footID = $foot.attr('id');

          var content = jquery('span', $foot).html();

          $foot.empty().html(n+1);

          var $l = jquery('
').attr('id', 'content_'+footID).html(content);
          jquery('#content #footnotes OL').append($l);
        });
      }

      var saveContent = function(_call) {
          var content = Aloha.getEditableById('contenteditor').getContents();
          var footnotes = {};

          _.each(jquery('#content #footnotes LI'), function(item, n) {
            footnotes[jquery(item).attr('id')] = jquery(item).html();
          });

          win.booktype.ui.notify(win.booktype._('saving_chapter', 'Saving chapter.'));

          win.booktype.sendToCurrentBook({"command": "chapter_save",
                                  "chapterID": chapterID,
                                  "content": content,
                                  "footnotes": footnotes,
                                  "continue": true,
                                  "comment": "",
                                  "author": "",
                                  "authorcomment": ""},
                                  function(data) {
                                    win.booktype.ui.notify();

                                    jquery('div.contentHeader span.info-message').html(win.booktype._('saved', 'Saved...'));
                                    setTimeout(function() { jquery('div.contentHeader span.info-message').empty(); }, 2000);

                                    if(!_.isUndefined(_call))
                                      _call();

                                    var doc = win.booktype.editor.getChapterWithID(chapterID);
                                    jquery(document).trigger('booktype-document-saved', [doc]);
                                  });

       }

        var _checkIfModified = function(callback, errback) {
          if(Aloha.getEditableById('contenteditor').isModified()) {
              var result = confirm(win.booktype._('content_has_been_modified', 'Content has been modified. Do you want to save it before?'));

              if(result) {
                saveContent(function() {
                   callback();
                });
                return true;
              }

//              errback();
//              return false;
          }
          callback();
          return true;
        }

      var _show = function() {
        var t = win.booktype.ui.getTemplate('templateAlohaToolbar');

        // Disable active options
        jquery('#button-toc').parent().removeClass('active');

        // Embed selected style
        win.booktype.editor.embedActiveStyle();

        jquery("DIV.contentHeader").html(t);
        jquery("DIV.contentHeader [rel=tooltip]").tooltip({container: 'body'});

        var t2 = win.booktype.ui.getTemplate('templateAlohaContent');
        jquery("#content").html(t2);

        jquery("#content #footnotes OL").empty();
        // fix Footnotes
        _fixFootnotes();

        Aloha.jQuery('#contenteditor').aloha();

        // HIDE
        jquery("#right-tabpane section[source_id=hold-tab]").hide();
        jquery('#hold-tab').hide();

        // Cancel editing
        jquery('#button-cancel').on('click', function() {
          win.booktype.editor.showTOC();

          jquery('#button-toc').parent().addClass('active');
        });

        // Save chapter
        jquery('#button-save').on('click', function() { saveContent(); });

        // Tabs
        tabs = [];

        if(win.booktype.editor.isEnabledTab('edit', 'chapters')) {
            var t1 = win.booktype.editor.createLeftTab('chapters-tab', 'big-icon-chapters', win.booktype._('table_of_contents', 'Table Of Contents'));
            var $panel = jquery("SECTION[source_id=chapters-tab]");

            jquery("BUTTON[rel=tooltip]", $panel).tooltip({container: 'body'});

            // Expand TOC
            jquery("BUTTON[rel=tooltip]", $panel).on('click', function() {
                jquery("BUTTON[rel=tooltip]", $panel).tooltip('destroy');
                // TODO
                // Must check if this content has been edited
                win.booktype.editor.showTOC();
            });

            t1.isOnTop = true;
            t1.onActivate = function() {
                jquery('UL.edit-toc', $panel).empty();

                jquery.each(win.booktype.editor.data.chapters.chapters, function(i, chap) {
                    if(chap.isSection) {
                      jquery('UL.edit-toc', $panel).append(jquery('

'+chap.title+'

'));
                    } else {
                      var $l = jquery('').text(chap.title);

                      $l.on('click', function() {
                          win.booktype.editor.editChapter(chap.chapterID);
                      });

                      var $a = jquery('
').wrapInner('
').wrapInner($l);
                      if(win.booktype.editor.getCurrentChapterID() == chap.chapterID)
                          ("LI", $a).addClass('active');

                      jquery('UL.edit-toc', $panel).append($a);
                    }

                });
                return false;
            };
            tabs.push(t1);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'attachments')) {
            var t2 = win.booktype.editor.createRightTab('attachments-tab', 'big-icon-attachments');
            t2.onActivate = function() {
                console.log('klikno na attachments');
            };

            tabs.push(t2);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'notes')) {
            var t3 = win.booktype.editor.createRightTab('notes-tab', 'big-icon-notes');
            t3.onActivate = function() {
                console.log('klikno na notes');
            };

            tabs.push(t3);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'history')) {
            var t4 = win.booktype.editor.createRightTab('history-tab', 'big-icon-history');
            t4.onActivate = function() {
                console.log('klikno na history');
            };

            tabs.push(t4);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'style')) {
            var t5 = win.booktype.editor.createLeftTab('style-tab', 'big-icon-style', win.booktype._('choose_your_design', 'Chose your Design'));

            var $container = jquery("section[source_id=style-tab]");
            jquery('A', $container).on('click', function() {
                  win.booktype.editor.setStyle(jquery(this).attr('data-style'));

                  return false;
            });

            t5.onActivate = function() {
              var $this = this;
              var $container = jquery("section[source_id=style-tab]");

            };

            tabs.push(t5);
        }

        win.booktype.editor.activateTabs(tabs);

        // Trigger events
        jquery(document).trigger('booktype-ui-panel-active', ['edit', this]);
      }

    var _hide = function(callback) {
      _checkIfModified(function() {
          jquery("DIV.contentHeader [rel=tooltip]").tooltip('destroy');

          Aloha.jQuery('#contenteditor').mahalo();
          jquery('#content').empty();
          jquery("DIV.contentHeader").empty();

          win.booktype.editor.deactivateTabs(tabs);
          win.booktype.editor.hideAllTabs();

          if(!_.isUndefined(callback))
            callback();
      }, function() {
          setTimeout(function() {
              jquery(".btn-toolbar label").removeClass("active");
          }, 0);
      });
    }

    var _init = function() {
      Aloha.bind('beforepaste', function(e) {
        console.log('*before paste*');
      });

      Aloha.bind('paste', function(e) {
        console.log('*before paste*');
      });

      // check if content has changed
      Aloha.bind('aloha-smart-content-changed', function(evt, args) {
              console.log('[aloha-smart-content-changed] ', args);
      })

      Aloha.bind('aloha-link-selected', function(a) {
      })

      Aloha.bind('aloha-image-selected', function(a) {
          console.log('Image selected');
      })

      Aloha.bind('aloha-image-unselected', function(a) {
          console.log('Image unselected');
      })

      Aloha.bind('aloha-editable-activated', function(evt, data) {
        console.log('[aloha-editable-activated]');
        // data.oldActive
        // data.editable
      });

     Aloha.bind('aloha-editable-created', function(e, editable) {
       console.log('[aloha-editable-created] ', editable);

       if(editable.obj.attr('id') == 'contenteditor') {
          win.scrollTo(0, 0);

          var $p = jquery('#contenteditor').find('p');

          if($p.length > 0) {
              // Select first paragraph
              newRange = new GENTICS.Utils.RangeObject();

              newRange.startContainer = newRange.endContainer = $p.get(0);

              newRange.startOffset = newRange.endOffset = 0;
              newRange.select();

              // This is needed for Firefox
              editable.obj.focus();
          }
        }
      });

    }

    var setChapterID = function(id) {
      chapterID = id;
    }

    return {'init': _init,
            'name': 'edit',
            'show': _show,
            'setChapterID': setChapterID,
            'saveContent': saveContent,
            'hide': _hide};

  }();

})(window, jQuery, _);<commit_msg>BK-925 After chapter has been saved content should have status unmodified<commit_after>/*
  This file is part of Booktype.
  Copyright (c) 2013 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>

  Booktype 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.

  Booktype 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 Booktype.  If not, see <http://www.gnu.org/licenses/>.
*/

(function(win, jquery, _) {

	jquery.namespace('win.booktype.editor.edit');

  win.booktype.editor.edit = function() {
      var chapterID = null;
      var tabs = [];

      var _fixFootnotes = function() {
        jquery('#content #footnotes OL').empty();

        _.each(jquery('sup.footnote', jquery('#contenteditor')), function(item, n) {
          var $foot = jquery(item);
          var footID = $foot.attr('id');

          var content = jquery('span', $foot).html();

          $foot.empty().html(n+1);

          var $l = jquery('
').attr('id', 'content_'+footID).html(content);
          jquery('#content #footnotes OL').append($l);
        });
      }

      var saveContent = function(_call) {
          var content = Aloha.getEditableById('contenteditor').getContents();
          var footnotes = {};

          _.each(jquery('#content #footnotes LI'), function(item, n) {
            footnotes[jquery(item).attr('id')] = jquery(item).html();
          });

          win.booktype.ui.notify(win.booktype._('saving_chapter', 'Saving chapter.'));

          win.booktype.sendToCurrentBook({"command": "chapter_save",
                                  "chapterID": chapterID,
                                  "content": content,
                                  "footnotes": footnotes,
                                  "continue": true,
                                  "comment": "",
                                  "author": "",
                                  "authorcomment": ""},
                                  function(data) {
                                    win.booktype.ui.notify();

                                    // Set content as unmodified after the save
                                    Aloha.getEditableById('contenteditor').setUnmodified();

                                    jquery('div.contentHeader span.info-message').html(win.booktype._('saved', 'Saved...'));
                                    setTimeout(function() { jquery('div.contentHeader span.info-message').empty(); }, 2000);

                                    if(!_.isUndefined(_call))
                                      _call();

                                    var doc = win.booktype.editor.getChapterWithID(chapterID);
                                    jquery(document).trigger('booktype-document-saved', [doc]);
                                  });

       }

        var _checkIfModified = function(callback, errback) {
          if(Aloha.getEditableById('contenteditor').isModified()) {
              var result = confirm(win.booktype._('content_has_been_modified', 'Content has been modified. Do you want to save it before?'));

              if(result) {
                saveContent(function() {
                   callback();
                });
                return true;
              }

//              errback();
//              return false;
          }
          callback();
          return true;
        }

      var _show = function() {
        var t = win.booktype.ui.getTemplate('templateAlohaToolbar');

        // Disable active options
        jquery('#button-toc').parent().removeClass('active');

        // Embed selected style
        win.booktype.editor.embedActiveStyle();

        jquery("DIV.contentHeader").html(t);
        jquery("DIV.contentHeader [rel=tooltip]").tooltip({container: 'body'});

        var t2 = win.booktype.ui.getTemplate('templateAlohaContent');
        jquery("#content").html(t2);

        jquery("#content #footnotes OL").empty();
        // fix Footnotes
        _fixFootnotes();

        Aloha.jQuery('#contenteditor').aloha();

        // HIDE
        jquery("#right-tabpane section[source_id=hold-tab]").hide();
        jquery('#hold-tab').hide();

        // Cancel editing
        jquery('#button-cancel').on('click', function() {
          win.booktype.editor.showTOC();

          jquery('#button-toc').parent().addClass('active');
        });

        // Save chapter
        jquery('#button-save').on('click', function() { saveContent(); });

        // Tabs
        tabs = [];

        if(win.booktype.editor.isEnabledTab('edit', 'chapters')) {
            var t1 = win.booktype.editor.createLeftTab('chapters-tab', 'big-icon-chapters', win.booktype._('table_of_contents', 'Table Of Contents'));
            var $panel = jquery("SECTION[source_id=chapters-tab]");

            jquery("BUTTON[rel=tooltip]", $panel).tooltip({container: 'body'});

            // Expand TOC
            jquery("BUTTON[rel=tooltip]", $panel).on('click', function() {
                jquery("BUTTON[rel=tooltip]", $panel).tooltip('destroy');
                // TODO
                // Must check if this content has been edited
                win.booktype.editor.showTOC();
            });

            t1.isOnTop = true;
            t1.onActivate = function() {
                jquery('UL.edit-toc', $panel).empty();

                jquery.each(win.booktype.editor.data.chapters.chapters, function(i, chap) {
                    if(chap.isSection) {
                      jquery('UL.edit-toc', $panel).append(jquery('

'+chap.title+'

'));
                    } else {
                      var $l = jquery('').text(chap.title);

                      $l.on('click', function() {
                          win.booktype.editor.editChapter(chap.chapterID);
                      });

                      var $a = jquery('
').wrapInner('
').wrapInner($l);
                      if(win.booktype.editor.getCurrentChapterID() == chap.chapterID)
                          ("LI", $a).addClass('active');

                      jquery('UL.edit-toc', $panel).append($a);
                    }

                });
                return false;
            };
            tabs.push(t1);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'attachments')) {
            var t2 = win.booktype.editor.createRightTab('attachments-tab', 'big-icon-attachments');
            t2.onActivate = function() {
                console.log('klikno na attachments');
            };

            tabs.push(t2);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'notes')) {
            var t3 = win.booktype.editor.createRightTab('notes-tab', 'big-icon-notes');
            t3.onActivate = function() {
                console.log('klikno na notes');
            };

            tabs.push(t3);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'history')) {
            var t4 = win.booktype.editor.createRightTab('history-tab', 'big-icon-history');
            t4.onActivate = function() {
                console.log('klikno na history');
            };

            tabs.push(t4);
        }

        if(win.booktype.editor.isEnabledTab('edit', 'style')) {
            var t5 = win.booktype.editor.createLeftTab('style-tab', 'big-icon-style', win.booktype._('choose_your_design', 'Chose your Design'));

            var $container = jquery("section[source_id=style-tab]");
            jquery('A', $container).on('click', function() {
                  win.booktype.editor.setStyle(jquery(this).attr('data-style'));

                  return false;
            });

            t5.onActivate = function() {
              var $this = this;
              var $container = jquery("section[source_id=style-tab]");

            };

            tabs.push(t5);
        }

        win.booktype.editor.activateTabs(tabs);

        // Trigger events
        jquery(document).trigger('booktype-ui-panel-active', ['edit', this]);
      }

    var _hide = function(callback) {
      _checkIfModified(function() {
          jquery("DIV.contentHeader [rel=tooltip]").tooltip('destroy');

          Aloha.jQuery('#contenteditor').mahalo();
          jquery('#content').empty();
          jquery("DIV.contentHeader").empty();

          win.booktype.editor.deactivateTabs(tabs);
          win.booktype.editor.hideAllTabs();

          if(!_.isUndefined(callback))
            callback();
      }, function() {
          setTimeout(function() {
              jquery(".btn-toolbar label").removeClass("active");
          }, 0);
      });
    }

    var _init = function() {
      Aloha.bind('beforepaste', function(e) {
        console.log('*before paste*');
      });

      Aloha.bind('paste', function(e) {
        console.log('*before paste*');
      });

      // check if content has changed
      Aloha.bind('aloha-smart-content-changed', function(evt, args) {
              console.log('[aloha-smart-content-changed] ', args);
      })

      Aloha.bind('aloha-link-selected', function(a) {
      })

      Aloha.bind('aloha-image-selected', function(a) {
          console.log('Image selected');
      })

      Aloha.bind('aloha-image-unselected', function(a) {
          console.log('Image unselected');
      })

      Aloha.bind('aloha-editable-activated', function(evt, data) {
        console.log('[aloha-editable-activated]');
        // data.oldActive
        // data.editable
      });

     Aloha.bind('aloha-editable-created', function(e, editable) {
       console.log('[aloha-editable-created] ', editable);

       if(editable.obj.attr('id') == 'contenteditor') {
          win.scrollTo(0, 0);

          var $p = jquery('#contenteditor').find('p');

          if($p.length > 0) {
              // Select first paragraph
              newRange = new GENTICS.Utils.RangeObject();

              newRange.startContainer = newRange.endContainer = $p.get(0);

              newRange.startOffset = newRange.endOffset = 0;
              newRange.select();

              // This is needed for Firefox
              editable.obj.focus();
          }
        }
      });

    }

    var setChapterID = function(id) {
      chapterID = id;
    }

    return {'init': _init,
            'name': 'edit',
            'show': _show,
            'setChapterID': setChapterID,
            'saveContent': saveContent,
            'hide': _hide};

  }();

})(window, jQuery, _);<|endoftext|>


<commit_before>/** @babel */
/** @jsx etch.dom */

import etch from 'etch'
import {CompositeDisposable} from 'atom'
import ModelObserver from '../models/model-observer'
import BranchView from '../views/branch-view'
import BranchMenuView from '../views/branch-menu-view'
import PushPullView from '../views/push-pull-view'
import PushPullMenuView from '../views/push-pull-menu-view'
import ChangedFilesCountView from '../views/changed-files-count-view'

export default class StatusBarTileController {
  constructor (props) {
    this.props = props
    this.checkout = this.checkout.bind(this)
    this.push = this.push.bind(this)
    this.pull = this.pull.bind(this)
    this.fetch = this.fetch.bind(this)
    this.disposables = new CompositeDisposable()
    this.branchMenuView = null
    this.pushPullMenuView = null
    this.repositoryObserver = new ModelObserver({
      fetchData: this.fetchRepositoryData.bind(this),
      didUpdate: () => etch.update(this)
    })
    this.repositoryObserver.setActiveModel(props.repository)
    etch.initialize(this)
  }

  update (props) {
    this.props = Object.assign({}, this.props, props)
    this.repositoryObserver.setActiveModel(props.repository)
    return etch.update(this)
  }

  render () {
    const modelData = this.repositoryObserver.getActiveModelData()

    const pushPullView = (
      <PushPullView
        ref='pushPullView'
        {...modelData}
      />
    )

    if (modelData) {
      return (

          <BranchView
            ref="branchView"
            {...modelData}
            workspace={this.props.workspace}
            checkout={this.checkout} />
          { modelData.remoteName ? pushPullView :  }
          <ChangedFilesCountView
            ref="changedFilesCountView"
            {...modelData}
            didClick={this.props.toggleGitPanel} />

      )
    } else {
      return

    }
  }

  writeAfterUpdate () {
    const modelData = this.repositoryObserver.getActiveModelData()
    if (modelData) {
      if (this.refs.pushPullView) this.createOrUpdatePushPullMenu(modelData)
      this.createOrUpdateBranchMenu(modelData)
    }
  }

  createOrUpdatePushPullMenu (modelData) {
    if (this.pushPullMenuView) {
      this.pushPullMenuView.update(modelData)
    } else {
      this.pushPullMenuView = new PushPullMenuView({
        ...modelData,
        workspace: this.props.workspace,
        push: this.push,
        pull: this.pull,
        fetch: this.fetch
      })

      this.disposables.add(
        atom.tooltips.add(this.refs.pushPullView.element, {
          item: this.pushPullMenuView,
          class: 'git-StatusBarTileController-tooltipMenu',
          trigger: 'click'
        })
      )
    }
  }

  createOrUpdateBranchMenu (modelData) {
    if (this.branchMenuView) {
      this.branchMenuView.update(modelData)
    } else {
      this.branchMenuView = new BranchMenuView({
        ...modelData,
        workspace: this.props.workspace,
        checkout: this.checkout
      })

      this.disposables.add(
        atom.tooltips.add(this.refs.branchView.element, {
          item: this.branchMenuView,
          class: 'git-StatusBarTileController-tooltipMenu',
          trigger: 'click'
        })
      )
    }
  }

  getActiveRepository () {
    return this.repositoryObserver.getActiveModel()
  }

  async fetchRepositoryData (repository) {
    const branchName = await repository.getCurrentBranch()
    const remoteName = await repository.getRemote(branchName)
    const changedFilesCount = await this.fetchChangedFilesCount(repository)
    const data = {
      branchName,
      remoteName,
      changedFilesCount,
      branches: await repository.getBranches()
    }
    if (remoteName) {
      data.aheadCount = await repository.getAheadCount(branchName),
      data.behindCount = await repository.getBehindCount(branchName),
      data.pullDisabled = changedFilesCount > 0
    }
    return data
  }

  async fetchChangedFilesCount (repository) {
    const changedFiles = new Set()
    for (let filePatch of await repository.getUnstagedChanges()) {
      changedFiles.add(filePatch.getPath())
    }
    for (let filePatch of await repository.getStagedChanges()) {
      changedFiles.add(filePatch.getPath())
    }
    return changedFiles.size
  }

  getLastModelDataRefreshPromise () {
    return this.repositoryObserver.getLastModelDataRefreshPromise()
  }

  checkout (branchName, options) {
    return this.getActiveRepository().checkout(branchName, options)
  }

  push () {
    const {branchName} = this.repositoryObserver.getActiveModelData()
    return this.getActiveRepository().push(branchName)
  }

  pull () {
    const {pullDisabled, branchName} = this.repositoryObserver.getActiveModelData()
    console.log('status bar pull');
    return pullDisabled ? Promise.resolve() : this.getActiveRepository().pull(branchName)
  }

  fetch () {
    const {branchName} = this.repositoryObserver.getActiveModelData()
    return this.getActiveRepository().fetch(branchName)
  }

  showPushPullMenu () {

    const hidePushPullMenu = (event) => {
      if (event.target !== menuElement && !menuElement.contains(event.target)) {
        window.removeEventListener('click', hidePushPullMenu, true)
        this.hidePushPullMenu()
      }
    }
    window.addEventListener('click', hidePushPullMenu, true)
    this.showingPushPullMenuView = true
  }

  destroy () {
    this.disposables.dispose()
  }
}
<commit_msg>:fire: console.log<commit_after>/** @babel */
/** @jsx etch.dom */

import etch from 'etch'
import {CompositeDisposable} from 'atom'
import ModelObserver from '../models/model-observer'
import BranchView from '../views/branch-view'
import BranchMenuView from '../views/branch-menu-view'
import PushPullView from '../views/push-pull-view'
import PushPullMenuView from '../views/push-pull-menu-view'
import ChangedFilesCountView from '../views/changed-files-count-view'

export default class StatusBarTileController {
  constructor (props) {
    this.props = props
    this.checkout = this.checkout.bind(this)
    this.push = this.push.bind(this)
    this.pull = this.pull.bind(this)
    this.fetch = this.fetch.bind(this)
    this.disposables = new CompositeDisposable()
    this.branchMenuView = null
    this.pushPullMenuView = null
    this.repositoryObserver = new ModelObserver({
      fetchData: this.fetchRepositoryData.bind(this),
      didUpdate: () => etch.update(this)
    })
    this.repositoryObserver.setActiveModel(props.repository)
    etch.initialize(this)
  }

  update (props) {
    this.props = Object.assign({}, this.props, props)
    this.repositoryObserver.setActiveModel(props.repository)
    return etch.update(this)
  }

  render () {
    const modelData = this.repositoryObserver.getActiveModelData()

    const pushPullView = (
      <PushPullView
        ref='pushPullView'
        {...modelData}
      />
    )

    if (modelData) {
      return (

          <BranchView
            ref="branchView"
            {...modelData}
            workspace={this.props.workspace}
            checkout={this.checkout} />
          { modelData.remoteName ? pushPullView :  }
          <ChangedFilesCountView
            ref="changedFilesCountView"
            {...modelData}
            didClick={this.props.toggleGitPanel} />

      )
    } else {
      return

    }
  }

  writeAfterUpdate () {
    const modelData = this.repositoryObserver.getActiveModelData()
    if (modelData) {
      if (this.refs.pushPullView) this.createOrUpdatePushPullMenu(modelData)
      this.createOrUpdateBranchMenu(modelData)
    }
  }

  createOrUpdatePushPullMenu (modelData) {
    if (this.pushPullMenuView) {
      this.pushPullMenuView.update(modelData)
    } else {
      this.pushPullMenuView = new PushPullMenuView({
        ...modelData,
        workspace: this.props.workspace,
        push: this.push,
        pull: this.pull,
        fetch: this.fetch
      })

      this.disposables.add(
        atom.tooltips.add(this.refs.pushPullView.element, {
          item: this.pushPullMenuView,
          class: 'git-StatusBarTileController-tooltipMenu',
          trigger: 'click'
        })
      )
    }
  }

  createOrUpdateBranchMenu (modelData) {
    if (this.branchMenuView) {
      this.branchMenuView.update(modelData)
    } else {
      this.branchMenuView = new BranchMenuView({
        ...modelData,
        workspace: this.props.workspace,
        checkout: this.checkout
      })

      this.disposables.add(
        atom.tooltips.add(this.refs.branchView.element, {
          item: this.branchMenuView,
          class: 'git-StatusBarTileController-tooltipMenu',
          trigger: 'click'
        })
      )
    }
  }

  getActiveRepository () {
    return this.repositoryObserver.getActiveModel()
  }

  async fetchRepositoryData (repository) {
    const branchName = await repository.getCurrentBranch()
    const remoteName = await repository.getRemote(branchName)
    const changedFilesCount = await this.fetchChangedFilesCount(repository)
    const data = {
      branchName,
      remoteName,
      changedFilesCount,
      branches: await repository.getBranches()
    }
    if (remoteName) {
      data.aheadCount = await repository.getAheadCount(branchName),
      data.behindCount = await repository.getBehindCount(branchName),
      data.pullDisabled = changedFilesCount > 0
    }
    return data
  }

  async fetchChangedFilesCount (repository) {
    const changedFiles = new Set()
    for (let filePatch of await repository.getUnstagedChanges()) {
      changedFiles.add(filePatch.getPath())
    }
    for (let filePatch of await repository.getStagedChanges()) {
      changedFiles.add(filePatch.getPath())
    }
    return changedFiles.size
  }

  getLastModelDataRefreshPromise () {
    return this.repositoryObserver.getLastModelDataRefreshPromise()
  }

  checkout (branchName, options) {
    return this.getActiveRepository().checkout(branchName, options)
  }

  push () {
    const {branchName} = this.repositoryObserver.getActiveModelData()
    return this.getActiveRepository().push(branchName)
  }

  pull () {
    const {pullDisabled, branchName} = this.repositoryObserver.getActiveModelData()
    return pullDisabled ? Promise.resolve() : this.getActiveRepository().pull(branchName)
  }

  fetch () {
    const {branchName} = this.repositoryObserver.getActiveModelData()
    return this.getActiveRepository().fetch(branchName)
  }

  showPushPullMenu () {

    const hidePushPullMenu = (event) => {
      if (event.target !== menuElement && !menuElement.contains(event.target)) {
        window.removeEventListener('click', hidePushPullMenu, true)
        this.hidePushPullMenu()
      }
    }
    window.addEventListener('click', hidePushPullMenu, true)
    this.showingPushPullMenuView = true
  }

  destroy () {
    this.disposables.dispose()
  }
}
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const Dependency = require("../Dependency");
const DependencyTemplate = require("../DependencyTemplate");

/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */

class AMDRequireArrayDependency extends Dependency {
	constructor(depsArray, range) {
		super();
		this.depsArray = depsArray;
		this.range = range;
	}

	get type() {
		return "amd require array";
	}
}

AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate extends DependencyTemplate {
	/**
	 * @param {Dependency} dependency the dependency for which the template should be applied
	 * @param {ReplaceSource} source the current replace source which can be modified
	 * @param {DependencyTemplateContext} templateContext the context object
	 * @returns {void}
	 */
	apply(dependency, source, { runtimeTemplate, moduleGraph, chunkGraph }) {
		const dep = /** @type {AMDRequireArrayDependency} */ (dependency);
		const content = this.getContent(dep, {
			runtimeTemplate,
			moduleGraph,
			chunkGraph
		});
		source.replace(dep.range[0], dep.range[1] - 1, content);
	}

	getContent(dep, { runtimeTemplate, moduleGraph, chunkGraph }) {
		const requires = dep.depsArray.map(dependency => {
			return this.contentForDependency(dependency, {
				runtimeTemplate,
				moduleGraph,
				chunkGraph
			});
		});
		return `[${requires.join(", ")}]`;
	}

	contentForDependency(dep, { runtimeTemplate, moduleGraph, chunkGraph }) {
		if (typeof dep === "string") {
			return dep;
		}

		if (dep.localModule) {
			return dep.localModule.variableName();
		} else {
			return runtimeTemplate.moduleExports({
				module: moduleGraph.getModule(dep),
				chunkGraph,
				request: dep.request
			});
		}
	}
};

module.exports = AMDRequireArrayDependency;
<commit_msg>feat(AMDRequireArrayDependency): make serializable<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const Dependency = require("../Dependency");
const DependencyTemplate = require("../DependencyTemplate");
const makeSerializable = require("../util/makeSerializable");

/** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
/** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */

class AMDRequireArrayDependency extends Dependency {
	constructor(depsArray, range) {
		super();

		this.depsArray = depsArray;
		this.range = range;
	}

	get type() {
		return "amd require array";
	}

	serialize(context) {
		const { write } = context;

		write(this.depsArray);
		write(this.range);

		super.serialize(context);
	}

	deserialize(context) {
		const { read } = context;

		this.depsArray = read();
		this.range = read();

		super.deserialize(context);
	}
}

makeSerializable(
	AMDRequireArrayDependency,
	"webpack/lib/dependencies/AMDRequireArrayDependency"
);

AMDRequireArrayDependency.Template = class AMDRequireArrayDependencyTemplate extends DependencyTemplate {
	/**
	 * @param {Dependency} dependency the dependency for which the template should be applied
	 * @param {ReplaceSource} source the current replace source which can be modified
	 * @param {DependencyTemplateContext} templateContext the context object
	 * @returns {void}
	 */
	apply(dependency, source, { runtimeTemplate, moduleGraph, chunkGraph }) {
		const dep = /** @type {AMDRequireArrayDependency} */ (dependency);
		const content = this.getContent(dep, {
			runtimeTemplate,
			moduleGraph,
			chunkGraph
		});
		source.replace(dep.range[0], dep.range[1] - 1, content);
	}

	getContent(dep, { runtimeTemplate, moduleGraph, chunkGraph }) {
		const requires = dep.depsArray.map(dependency => {
			return this.contentForDependency(dependency, {
				runtimeTemplate,
				moduleGraph,
				chunkGraph
			});
		});
		return `[${requires.join(", ")}]`;
	}

	contentForDependency(dep, { runtimeTemplate, moduleGraph, chunkGraph }) {
		if (typeof dep === "string") {
			return dep;
		}

		if (dep.localModule) {
			return dep.localModule.variableName();
		} else {
			return runtimeTemplate.moduleExports({
				module: moduleGraph.getModule(dep),
				chunkGraph,
				request: dep.request
			});
		}
	}
};

module.exports = AMDRequireArrayDependency;
<|endoftext|>


<commit_before>'use strict';

const { extend } = require('underscore');

const debug = require('abacus-debug')('abacus-usage-metering-message-handler');
const edebug = require('abacus-debug')('e-abacus-usage-metering-message-handler');

class MessageHandler {
  constructor(normalizer, meter, accumulatorClient, outputDb, errorDb) {
    this.normalizer = normalizer;
    this.meter = meter;
    this.accumulatorClient = accumulatorClient;
    this.outputDb = outputDb;
    this.errorDb = errorDb;
  }

  async handle(inputUsageDocument) {
    try {
      debug('Start processing message: %j', inputUsageDocument);
      const normalizedUsageDoc = await this.normalizer.normalizeUsage(inputUsageDocument);
      const meteredUsageDoc = await this.meter.meterUsage(normalizedUsageDoc);
      const outputDoc = await this.accumulatorClient.postUsage(meteredUsageDoc);
      await this.outputDb.put(outputDoc);
    } catch(e) {
      edebug('Error while processing document: %о', e);
      if(e.isPlanBusinessError)
        await this.errorDb.put(extend({}, inputUsageDocument, { error: e }));
      else
        throw e;
    }
  }
}

module.exports.MessageHandler = MessageHandler;
<commit_msg>%o substituion correction (#951)<commit_after>'use strict';

const { extend } = require('underscore');

const debug = require('abacus-debug')('abacus-usage-metering-message-handler');
const edebug = require('abacus-debug')('e-abacus-usage-metering-message-handler');

class MessageHandler {
  constructor(normalizer, meter, accumulatorClient, outputDb, errorDb) {
    this.normalizer = normalizer;
    this.meter = meter;
    this.accumulatorClient = accumulatorClient;
    this.outputDb = outputDb;
    this.errorDb = errorDb;
  }

  async handle(inputUsageDocument) {
    try {
      debug('Start processing message: %j', inputUsageDocument);
      const normalizedUsageDoc = await this.normalizer.normalizeUsage(inputUsageDocument);
      const meteredUsageDoc = await this.meter.meterUsage(normalizedUsageDoc);
      const outputDoc = await this.accumulatorClient.postUsage(meteredUsageDoc);
      await this.outputDb.put(outputDoc);
    } catch(e) {
      edebug('Error while processing document: %o', e);
      if(e.isPlanBusinessError)
        await this.errorDb.put(extend({}, inputUsageDocument, { error: e }));
      else
        throw e;
    }
  }
}

module.exports.MessageHandler = MessageHandler;
<|endoftext|>