<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://a.tiles.mapbox.com/v3/cartodb.map-4xtxp73f.jsonp',
          maxZoom: 17,
          name: 'Graphite',
          className: "mapbox_graphite"
        },
        {
          url: 'http://tile.stamen.com/toner/{z}/{x}/{y}.png',
          maxZoom: 17,
          name: 'Toner',
          className: "mapbox_toner"
        },
        {
          url: 'http://a.tiles.mapbox.com/v3/mapbox.mapbox-light/{z}/{x}/{y}.png',
          maxZoom: 17,
          name: 'Light',
          className: "mapbox_light"
        },
        //'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,
          name: 'Streets',
          className: "mapbox_streets"
        },
        {
          url: 'http://a.tiles.mapbox.com/v3/cartodb.map-uulyudas.jsonp',
          maxZoom: 17,
          name: 'Warden',
          className: "mapbox_warden"
        }

      ];

      this.baseLayers = this.user.layers;
      _(layers).map(function(m) {

        self.baseLayers.add(new cdb.admin.TileLayer({
          name:        m.name,
          className:   m.className,
          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.sqlView.reset([]);
          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>Removes warden & graphite layers<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://a.tiles.mapbox.com/v3/cartodb.map-4xtxp73f.jsonp',
          maxZoom: 17,
          name: 'Graphite',
          className: "mapbox_graphite"
        },*/
        {
          url: 'http://tile.stamen.com/toner/{z}/{x}/{y}.png',
          maxZoom: 17,
          name: 'Toner',
          className: "mapbox_toner"
        },
        {
          url: 'http://a.tiles.mapbox.com/v3/mapbox.mapbox-light/{z}/{x}/{y}.png',
          maxZoom: 17,
          name: 'Light',
          className: "mapbox_light"
        },
        //'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,
          name: 'Streets',
          className: "mapbox_streets"
        }
        /*{
          url: 'http://a.tiles.mapbox.com/v3/cartodb.map-uulyudas.jsonp',
          maxZoom: 17,
          name: 'Warden',
          className: "mapbox_warden"
        }*/

      ];

      this.baseLayers = this.user.layers;
      _(layers).map(function(m) {

        self.baseLayers.add(new cdb.admin.TileLayer({
          name:        m.name,
          className:   m.className,
          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.sqlView.reset([]);
          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();
        })
      }
    });

});
<|endoftext|>


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

    // prepare onload
    // if($('.custom-select').length > 0) {

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

            ,selectOptions = select.find('option')
            ,caption = $('

')
            ,captionText = $('

')
            ,options = $('

')
            ,searchBox = $('

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

')
        ;

        select.hide();

        searchBox.addClass('search-box');
        caption.addClass('caption expand');
        captionText.addClass('text');
        options.addClass('options');
        list.addClass('custom-select-list');
        searchTextBox.attr('type', 'text');

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

        selectOptions.each(function (i, o) {
            o = $(o);
            var li = $('

');

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

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

        options.append(list);

        setActionClickItem();
    });

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

    // find
    $('.custom-select input[type=text]').on('keyup', function (e) {
        var
            inputText = $(this)
            ,wrapper = inputText.closest('.custom-select')
            ,resultList = null
            ,resultOptions = null
            ,options = wrapper.find('ul.custom-select-list li')
            ,liText = null
            ,search = null
            ,previousText = null
            ,found = null
            ,subsequentText = null
        ;

        if (wrapper.find('ul.search-result-list').length === 0) {
            resultList = $('

').addClass('search-result-list');
            resultList.insertAfter(wrapper.find('.search-box'));
        } else {
            resultList = wrapper.find('ul.search-result-list');
            resultList.empty();
        }

        resultOptions = resultList.find('li');

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

            options.each(function (i, li) {
                liText = li.textContent.trim();

                search = liText.toLowerCase().search(inputText.val().toLowerCase());
                if (search > -1) {
                    resultList.show();
                    options.parent().hide();

                    previousText = liText.slice(0, search);
                    found = liText.slice(previousText.length, previousText.length + inputText.val().length);
                    subsequentText = liText.slice(previousText.length + found.length, liText.length);

                    var newLi = $('
' + previousText + '' + found + '' + subsequentText + '
');

                    newLi.attr('data-value', $(li).data('value'));

                    if (resultOptions.length > 0) {
                        resultOptions.each(function (i, addedLi) {
                            if (addedLi.textContent === liText) {
                                $(addedLi).replaceWith(newLi);
                            } else {
                                resultList.prepend(newLi);
                            }
                        });
                    } else {
                        resultList.prepend(newLi);
                    }

                    setActionClickItem();
                }
            });
        } else {
            options.parent().show();
            resultList.hide();
        }
    });

});

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

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

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

        captionText.text(selected.text());
        wrapper.find('.options').hide();

        toggleCaptionClass();
    });
}

var toggleCaptionClass = function(){
    $('.custom-select .caption').toggleClass('retract', 'expand');
}

// click out
$(document).click(function(e) {
    var options = $('.custom-select .options');

    if( $(e.target).closest('.custom-select').length === 0 ) {
        if( options.is(':visible') ) {
            options.hide();
            toggleCaptionClass();
        }
    }
});
<commit_msg>refatora select<commit_after>$(function () {
    'use strict';

    // prepare onload
    // if( $('.custom-select').length > 0 ) {

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

            ,selectOptions = select.find('option')
            ,caption = $('

')
            ,captionText = $('

')
            ,options = $('

')
            ,searchBox = $('

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

')
        ;

        select.hide();

        searchBox.addClass('search-box');
        caption.addClass('caption expand');
        captionText.addClass('text');
        options.addClass('options');
        list.addClass('custom-select-list');
        searchTextBox.attr('type', 'text');

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

        selectOptions.each(function (i, o) {
            o = $(o);
            var
                li = $('

');

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

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

        options.append(list);

        setActionClickItem();
    });

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

    // find
    $('.custom-select input[type=text]').on('keyup', function (e) {
        var
            inputText = $(this)
            ,wrapper = inputText.closest('.custom-select')
            ,resultList = null
            ,resultOptions = null
            ,options = wrapper.find('ul.custom-select-list li')
            ,liText = null
            ,search = null
            ,previousText = null
            ,found = null
            ,subsequentText = null
        ;

        if (wrapper.find('ul.search-result-list').length === 0) {
            resultList = $('

').addClass('search-result-list');
            resultList.insertAfter(wrapper.find('.search-box'));
        } else {
            resultList = wrapper.find('ul.search-result-list');
            resultList.empty();
        }

        resultOptions = resultList.find('li');

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

            options.each(function (i, li) {
                liText = li.textContent.trim();

                search = liText.toLowerCase().search(inputText.val().toLowerCase());
                if (search > -1) {
                    resultList.show();
                    options.parent().hide();

                    previousText = liText.slice(0, search);
                    found = liText.slice(previousText.length, previousText.length + inputText.val().length);
                    subsequentText = liText.slice(previousText.length + found.length, liText.length);

                    var
                        newLi = $('
' + previousText + '' + found + '' + subsequentText + '
');

                    newLi.attr('data-value', $(li).data('value'));

                    if (resultOptions.length > 0) {
                        resultOptions.each(function (i, addedLi) {
                            if (addedLi.textContent === liText) {
                                $(addedLi).replaceWith(newLi);
                            } else {
                                resultList.prepend(newLi);
                            }
                        });
                    } else {
                        resultList.prepend(newLi);
                    }

                    setActionClickItem();
                }
            });
        } else {
            options.parent().show();
            resultList.hide();
        }
    });

});

//reset

//select onclick
// por que action?
//var setActionClickItem = function() {
var setActionClickItem = function() {

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

        // remove seleção
        select.find('option:selected').attr('selected', false);

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

        captionText.text(selected.text());
        wrapper.find('.options').hide();

        toggleCaptionClass();
    });
}

var toggleCaptionClass = function(){
    $('.custom-select .caption').toggleClass('retract', 'expand');
}

// click out
$(document).click(function(e) {
    var
        options = $('.custom-select .options');

    if( $(e.target).closest('.custom-select').length === 0 ) {
        if( options.is(':visible') ) {
            options.hide();
            toggleCaptionClass();
        }
    }
});
<|endoftext|>


<commit_before>// Send reply to client.
// We expect, to have:
// - env.res
//   - body
//   - headers

'use strict';

const http        = require('http');
const compression = require('compression')();

let valid_headers = {};
[ // http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
  'Access-Control-Allow-Origin',
  'Accept-Ranges',
  'Age',
  'Allow',
  'Cache-Control',
  'Connection',
  'Content-Encoding',
  'Content-Language',
  'Content-Length',
  'Content-Location',
  'Content-MD5',
  'Content-Disposition',
  'Content-Security-Policy',
  'Content-Security-Policy-Report-Only',
  'Content-Range',
  'Content-Type',
  'Date',
  'ETag',
  'Expires',
  'Last-Modified',
  'Link',
  'Location',
  'P3P',
  'Pragma',
  'Proxy-Authenticate',
  'Refresh',
  'Retry-After',
  'Server',
  'Set-Cookie',
  'Strict-Transport-Security',
  'Trailer',
  'Transfer-Encoding',
  'Vary',
  'Via',
  'Warning',
  'WWW-Authenticate',
  // Common non-standard response headers
  'X-Frame-Options',
  'X-XSS-Protection',
  'X-Content-Security-Policy',
  'X-WebKit-CSP',
  'X-Content-Type-Options',
  'X-Powered-By',
  'X-UA-Compatible'
].forEach(hdr => { valid_headers[hdr] = true; });

////////////////////////////////////////////////////////////////////////////////

// Note, we also listen `responder:bin` to unify logging & error responding

const CHANNELS = [ 'responder:http', 'responder:rpc', 'responder:bin' ];

module.exports = function (N) {

  N.wire.after(CHANNELS, { priority: 100 }, function response_compress(env, callback) {
    compression(env.origin.req, env.origin.res, callback);
  });

  N.wire.after(CHANNELS, { priority: 100 }, function response_send(env) {
    let res = env.origin.res,
        headers = env.headers,
        body = env.body,
        statusCode;

    // If someone already sent reply - do nothing
    if (res.finished) return;

    // That should not happen, because custom senders should wait
    // stream end.
    if (res.headerSent) return;

    //
    // Set some obligatory headers
    //

    headers.Server = headers.Server || 'Sansun Calakci';
    // added by node automatically
    // headers['Date'] = headers['Date'] || new Date).toUTCString();

    //
    // Remove Accept-Ranges if it wasn't explicitly set
    //

    if (!headers['Accept-Ranges']) {
      try {
        res.removeHeader('Accept-Ranges');
      } catch (err) {
        N.logger.error('send_reply: %s\n%s', err.stack, JSON.stringify({
          ip:        env.req.ip,
          url:       env.origin.req.url,
          request:   env.origin.req.method,
          responder: env.req.type,
          apiPath:   env.method,
          params:    env.params
        }, null, 2));
      }
    }

    //
    // set headers
    //

    for (let [ name, value ] of Object.entries(headers)) {
      // Check if header registered, since
      // one can mistype capitalization and name
      if (!valid_headers[name]) {
        N.logger.fatal('send_reply: Got wrong header %s in method %s', name, env.method);
      }

      if (value === null) {
        res.removeHeader(name);
        continue;
      }
      res.setHeader(name, value);
    }

    //
    // should not happen
    //

    if (!res.getHeader('Content-Type')) {
      N.logger.fatal('send_reply: Required header Content-Type was not set in %s', env.method);
    }

    //
    // When body is given, it MUST be a Buffer or a String
    // (this error should not happen)
    //

    if (body && !Buffer.isBuffer(body) && typeof body !== 'string') {
      statusCode = N.io.APP_ERROR;
      body       = http.STATUS_CODES[statusCode];
      N.logger.fatal('send_reply: body MUST be a Buffer, String or Null/Undefined. in %s',
                     env.method);
    }

    // set status code and send body (if any)
    res.statusCode = env.status;
    res.end(body);
  });
};
<commit_msg>Fix error messages in send_reply<commit_after>// Send reply to client.
// We expect, to have:
// - env.res
//   - body
//   - headers

'use strict';

const http        = require('http');
const compression = require('compression')();

let valid_headers = {};
[ // http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
  'Access-Control-Allow-Origin',
  'Accept-Ranges',
  'Age',
  'Allow',
  'Cache-Control',
  'Connection',
  'Content-Encoding',
  'Content-Language',
  'Content-Length',
  'Content-Location',
  'Content-MD5',
  'Content-Disposition',
  'Content-Security-Policy',
  'Content-Security-Policy-Report-Only',
  'Content-Range',
  'Content-Type',
  'Date',
  'ETag',
  'Expires',
  'Last-Modified',
  'Link',
  'Location',
  'P3P',
  'Pragma',
  'Proxy-Authenticate',
  'Refresh',
  'Retry-After',
  'Server',
  'Set-Cookie',
  'Strict-Transport-Security',
  'Trailer',
  'Transfer-Encoding',
  'Vary',
  'Via',
  'Warning',
  'WWW-Authenticate',
  // Common non-standard response headers
  'X-Frame-Options',
  'X-XSS-Protection',
  'X-Content-Security-Policy',
  'X-WebKit-CSP',
  'X-Content-Type-Options',
  'X-Powered-By',
  'X-UA-Compatible'
].forEach(hdr => { valid_headers[hdr] = true; });

////////////////////////////////////////////////////////////////////////////////

// Note, we also listen `responder:bin` to unify logging & error responding

const CHANNELS = [ 'responder:http', 'responder:rpc', 'responder:bin' ];

module.exports = function (N) {

  N.wire.after(CHANNELS, { priority: 100 }, function response_compress(env, callback) {
    compression(env.origin.req, env.origin.res, callback);
  });

  function report_error(env, message) {
    N.logger.error('send_reply: %s\n%s', message, JSON.stringify({
      ip:        env.req.ip,
      url:       env.origin.req.url,
      request:   env.origin.req.method,
      responder: env.req.type,
      apiPath:   env.method,
      params:    env.params
    }, null, 2));
  }

  N.wire.after(CHANNELS, { priority: 100 }, function response_send(env) {
    let res = env.origin.res,
        headers = env.headers,
        body = env.body,
        statusCode;

    // If someone already sent reply - do nothing
    if (res.finished) return;

    // That should not happen, because custom senders should wait
    // stream end.
    if (res.headerSent) return;

    //
    // Set some obligatory headers
    //

    headers.Server = headers.Server || 'Sansun Calakci';
    // added by node automatically
    // headers['Date'] = headers['Date'] || new Date).toUTCString();

    //
    // Remove Accept-Ranges if it wasn't explicitly set
    //

    if (!headers['Accept-Ranges']) {
      try {
        res.removeHeader('Accept-Ranges');
      } catch (err) {
        report_error(env, err.stack);
      }
    }

    //
    // set headers
    //

    for (let [ name, value ] of Object.entries(headers)) {
      // Check if header registered, since
      // one can mistype capitalization and name
      if (!valid_headers[name]) {
        report_error(env, `Got wrong header "${name}"`);
      }

      if (value === null) {
        res.removeHeader(name);
        continue;
      }
      res.setHeader(name, value);
    }

    //
    // should not happen
    //

    if (!res.getHeader('Content-Type')) {
      report_error(env, 'Required header Content-Type was not set');
    }

    //
    // When body is given, it MUST be a Buffer or a String
    // (this error should not happen)
    //

    if (body && !Buffer.isBuffer(body) && typeof body !== 'string') {
      statusCode = N.io.APP_ERROR;
      body       = http.STATUS_CODES[statusCode];
      report_error(env, 'body MUST be a Buffer, String or Null/Undefined');
    }

    // set status code and send body (if any)
    res.statusCode = env.status;
    res.end(body);
  });
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import ReactionPickerView from '../views/reaction-picker-view';
import {RefHolderPropType} from '../prop-types';

export default class ReactionPickerController extends React.Component {
  static propTypes = {
    addReaction: PropTypes.func.isRequired,
    removeReaction: PropTypes.func.isRequired,

    tooltipHolder: RefHolderPropType.isRequired,
  }

  render() {
    return (
      <ReactionPickerView
        addReactionAndClose={this.addReactionAndClose}
        removeReactionAndClose={this.removeReactionAndClose}
        {...this.props}
      />
    );
  }

  addReactionAndClose = async content => {
    await this.props.addReaction(content);
    this.props.tooltipHolder.map(tooltip => tooltip.dispose());
  }

  removeReactionAndClose = async content => {
    await this.props.removeReaction(content);
    this.props.tooltipHolder.map(tooltip => tooltip.dispose());
  }
}
<commit_msg>metrics for adding/removing emoji reactions<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import ReactionPickerView from '../views/reaction-picker-view';
import {RefHolderPropType} from '../prop-types';
import {addEvent} from '../reporter-proxy';

export default class ReactionPickerController extends React.Component {
  static propTypes = {
    addReaction: PropTypes.func.isRequired,
    removeReaction: PropTypes.func.isRequired,

    tooltipHolder: RefHolderPropType.isRequired,
  }

  render() {
    return (
      <ReactionPickerView
        addReactionAndClose={this.addReactionAndClose}
        removeReactionAndClose={this.removeReactionAndClose}
        {...this.props}
      />
    );
  }

  addReactionAndClose = async content => {
    await this.props.addReaction(content);
    addEvent('add-emoji-reaction', {package: 'github'});
    this.props.tooltipHolder.map(tooltip => tooltip.dispose());
  }

  removeReactionAndClose = async content => {
    await this.props.removeReaction(content);
    addEvent('remove-emoji-reaction', {package: 'github'});
    this.props.tooltipHolder.map(tooltip => tooltip.dispose());
  }
}
<|endoftext|>


<commit_before>const smash = require("../../../smash.js");
const logger = smash.logger("DynamodbEvent");
const errorUtil = new smash.SmashError(logger);
const EventType = require("./lib/eventType.js");
const Event = require("./lib/event.js");

class DynamodbEvent {
    constructor() {
        this._events = [];
    }

    get smash() {
        return smash;
    }

    _matchEvents(event) {
        const events = [];
        for (let i = 0, length = this._events.length; i < length; i++) {
            if (this._events[i].match(event) === true) {
                events.push(this._events[i]);
            }
        }
        return events;
    }

    handleEvent(rawEvent, context, callback) {
        if (typeof callback !== 'function') {
            throw new Error("Third parameter of handleEvent() must be a function, " + errorUtil.typeOf(callback) + " given");
        }
        this._callback = callback;
        const event = new Event(rawEvent, context, this);
        const matchedEvents = this._matchEvents(event);
        if (matchedEvents.length === 0) {
            logger.info("No event found");
            this.terminate(new Error("No event found"));
        } else if (matchedEvents.length > 1) {
            logger.error("More than 1 match for the event");
            this.terminate(new Error("More than 1 match for the event"));
        } else {
            logger.info("Match event " + event.type + " " + event.table + "in env: " + smash.getEnv("ENV"));
            smash.setCurrentEvent(event);
            matchedEvents[0].callback.call(smash, event);
            return this;
        }
    }

    terminate(error, data) {
        if (error) {
            logger.info("Result => Failure");
        } else {
            logger.info("Result => Success");
        }
        this._callback(error, data);
        return this;
    }

    isEvent(event) {
        if (!event.Records || !event.Records[0] || event.Records[0].EventSource !== 'aws:dynamodb') {
            return false;
        }
        return true;
    }

    event(route, callback) {
        const event = new EventType(route, callback);
        this._events.push(event);
        return this;
    }

    getHandlers() {
        return this._events;
    }

    expose() {
        return [
            {
                "functionName": "dynamodbEvent",
                "function": "event"
            }
        ];
    }
}

module.exports = DynamodbEvent;
<commit_msg>Fix bug with dynamodb event<commit_after>const smash = require("../../../smash.js");
const logger = smash.logger("DynamodbEvent");
const errorUtil = new smash.SmashError(logger);
const EventType = require("./lib/eventType.js");
const Event = require("./lib/event.js");

class DynamodbEvent {
    constructor() {
        this._events = [];
    }

    get smash() {
        return smash;
    }

    _matchEvents(event) {
        const events = [];
        for (let i = 0, length = this._events.length; i < length; i++) {
            if (this._events[i].match(event) === true) {
                events.push(this._events[i]);
            }
        }
        return events;
    }

    handleEvent(rawEvent, context, callback) {
        if (typeof callback !== 'function') {
            throw new Error("Third parameter of handleEvent() must be a function, " + errorUtil.typeOf(callback) + " given");
        }
        this._callback = callback;
        const event = new Event(rawEvent, context, this);
        const matchedEvents = this._matchEvents(event);
        if (matchedEvents.length === 0) {
            logger.info("No event found");
            this.terminate(new Error("No event found"));
        } else if (matchedEvents.length > 1) {
            logger.error("More than 1 match for the event");
            this.terminate(new Error("More than 1 match for the event"));
        } else {
            logger.info("Match event " + event.type + " " + event.table + "in env: " + smash.getEnv("ENV"));
            smash.setCurrentEvent(event);
            matchedEvents[0].callback.call(smash, event);
            return this;
        }
    }

    terminate(error, data) {
        if (error) {
            logger.info("Result => Failure");
        } else {
            logger.info("Result => Success");
        }
        this._callback(error, data);
        return this;
    }

    isEvent(event) {
        if (event.Records && event.Records[0] && event.Records[0].eventSource === 'aws:dynamodb') {
            return true;
        }
        return false;
    }

    event(route, callback) {
        const event = new EventType(route, callback);
        this._events.push(event);
        return this;
    }

    getHandlers() {
        return this._events;
    }

    expose() {
        return [
            {
                "functionName": "dynamodbEvent",
                "function": "event"
            }
        ];
    }
}

module.exports = DynamodbEvent;
<|endoftext|>


<commit_before><commit_msg>Extract helper for creating tooltip bubbles<commit_after><|endoftext|>


<commit_before>var _ = require('lodash');

exports.mttr = function mttr(req, res) {
  var end = parseInt(new Date().valueOf() / 1000);
  var start = end - 86400 * 7;
  var mttrArray = {};

  var Benchs = req.app.get('models').Benchs;
  Benchs.fetchHistory(start, end, function(error, histories) {
    if (error) {
      return res.status(400).json(error);
    }

    histories.forEach(function(history) {
      var hostname = history.data.hostname;
      var project = hostname.split('-')[0];
      var during = parseInt((history.data.releaseAt - history.data.markedAt) / 1000);
      if (!_.has(mttrArray, project)) {
        mttrArray[project] = {
          'project': project,
          'hosts': [],
          'mttr': 0,
          'rate': 0,
        };
      }
      if (-1 === mttrArray[project].hosts.indexOf(hostname)) {
        mttrArray[project].hosts.push(hostname);
      }
      mttrArray[project].mttr += during;
      mttrArray[project].rate = parseFloat(mttrArray[project].mttr / (7 * 86400) / mttrArray[project].hosts.length).toFixed(4);
    });
    res.json(mttrArray);
  });
};

exports.vmmRate = function vmmRate(req, res) {

};
<commit_msg>Remove unused method<commit_after>var _ = require('lodash');

exports.mttr = function mttr(req, res) {
  var end = parseInt(new Date().valueOf() / 1000);
  var start = end - 86400 * 7;
  var mttrArray = {};

  var Benchs = req.app.get('models').Benchs;
  Benchs.fetchHistory(start, end, function(error, histories) {
    if (error) {
      return res.status(400).json(error);
    }

    histories.forEach(function(history) {
      var hostname = history.data.hostname;
      var project = hostname.split('-')[0];
      var during = parseInt((history.data.releaseAt - history.data.markedAt) / 1000);
      if (!_.has(mttrArray, project)) {
        mttrArray[project] = {
          'project': project,
          'hosts': [],
          'mttr': 0,
          'rate': 0,
        };
      }
      if (-1 === mttrArray[project].hosts.indexOf(hostname)) {
        mttrArray[project].hosts.push(hostname);
      }
      mttrArray[project].mttr += during;
      mttrArray[project].rate = parseFloat(mttrArray[project].mttr / (7 * 86400) / mttrArray[project].hosts.length).toFixed(4);
    });
    res.json(mttrArray);
  });
};
<|endoftext|>


<commit_before>/*globals ExpandableInputs, self, jml */
/*jslint todo:true*/
(function () {'use strict';

var
	emit = self.port.emit,
	on = self.port.on,
	options = self.options,
	locale = options.locale,
	ei_locale = options.ei_locale,
	args = new ExpandableInputs({
		locale: ei_locale,
		table: 'executableTable',
		namespace: 'args',
		label: ei_locale.args_num,
		inputSize: 60,
		rows: 1 // Might perhaps make this optional to save space, but this triggers creation of a textarea so args could be more readable (since to auto-escape newlines as needed)
	}),
	urls = new ExpandableInputs({
		locale: ei_locale,
		table: 'URLArguments',
		namespace: 'urls',
		label: ei_locale.url_num,
		inputSize: 40,
		inputType: 'url'
	}),
	files = new ExpandableInputs({
		locale: ei_locale,
		table: 'fileArguments',
		namespace: 'files',
		label: ei_locale.file_num,
		inputSize: 25,
		inputType: 'file',
		selects: true
	});

// POLYFILLS
Array.from = function (arg) {
	return [].slice.call(arg);
};

// UTILITIES
function l (msg) {
	console.log(msg);
}
function $ (sel) {
	return document.querySelector(sel);
}
function $$ (sel) {
	return document.querySelectorAll(sel);
}
function forSel (sel, cb) {
	Array.from($$(sel)).forEach(cb);
}
function _ (key) {
	return locale[key] || '(Non-internationalized string--FIXME!)' + key;
}

// ADD EVENTS

document.title = _("title");
jml('div', [
	['div', (function (options) {
		var atts = {id: 'names'};
		if (options.itemType === 'one-off') {
			atts.hidden = true;
		}
		return atts;
	}(options)), [
		['select', {id: 'selectNames', size: 50, $on: {click: function (e) {
			if (e.target.nodeName.toLowerCase() !== 'option') {
				return;
			}
			if (e.target.value === '') { // Create new command

			}
			else {

			}
		}}}, [
			['option', {value: ''}, [_("create_new_command")]],
			['option', ['Name2']]
		]]
	]],
	['div', (function (options) {
		var atts = {id: 'main'};
		atts.className = options.itemType === 'one-off' ? 'closed' : 'open';
		return atts;
	}(options)), [
		['button', {id: 'showNames', $on: {click: function () {
			$('#names').hidden = !$('#names').hidden;
			var showNames = $('#showNames');
			if (!$('#names').hidden) {
				$('#main').className = 'open';
				showNames.replaceChild(document.createTextNode(_("lt")), showNames.firstChild);
			}
			else {
				$('#main').className = 'closed';
				showNames.replaceChild(document.createTextNode(_("gt")), showNames.firstChild);
			}
		}}}, [
			_(options.itemType === 'one-off' ? "gt" : "lt")
		]],
		['div', {id: 'processExecuted', style: 'visibility:hidden;'}, [
			_("Process executed")
		]],
		['div', {id: 'substitutions-explanation-container'}, [
			['h3', [_("Substitutions explained")]],
			['div', {id: 'substitutions-explanation'}, [
				_("Substitution_sequences_allow"),
				['br'],['br'],
				_("prefixes_can_be_applied"),
				['dl', [
						'save-temp', 'ucencode-', 'uencode-', 'escquotes-'
					].reduce(function (children, prefix) {
						children.push(['dt', [prefix]]);
						children.push(['dd', [_("prefix_" + prefix)]]);
						return children;
					}, [])
				],
				['b', [_("Sequences")]],
				['dl', [
						'eval', 'pageURL', 'pageTitle', 'pageHTML', 'bodyText',
						'selectedHTML', 'selectedText', 'linkPageURL',
						'linkPageURLAsNativePath', 'linkPageTitle',
						'linkBodyText', 'linkPageHTML', 'imageURL',
						'imageDataURL', 'imageDataBinary'
					].reduce(function (children, seq) {
						children.push(['dt', [seq]]);
						children.push(['dd', [_("seq_" + seq)]]);
						return children;
					}, [])
				]
			]]
		]],
		['div', {id: 'substitutions-used-container'}, [
			['h3', [_("Substitutions used")]],
			['div', {id: 'substitutions-used'}, [
				_("currently_available_sequences"),
				['br'],['br'],
				/*
				['dl', [
					['dt', ['save-temp-']], ['dd'],
					['dt', ['ucencode-']], ['dd'],
					['dt', ['uencode-']], ['dd'],
					['dt', ['escquotes-']], ['dd'],
				]],
				*/
				['b', [_("Sequences")]],
				['dl', [
						'eval', 'pageURL', 'pageTitle', 'pageHTML', 'bodyText',
						'selectedHTML', 'selectedText', 'linkPageURL',
						'linkPageURLAsNativePath', 'linkPageTitle',
						'linkBodyText', 'linkPageHTML', 'imageURL',
						'imageDataURL', 'imageDataBinary'
					].reduce(function (children, seq) {
						children.push(['dt', [seq]]);
						children.push(['dd']);
						return children;
					}, [])
				]
			]]
		]],
		['div', {id: 'command-name-section'}, [
			['label', {title: _("if_present_command_saved")}, [
				_("Command name") + ' ',
				['input', (function (options) {
					var atts = {id: 'command-name', size: '55'};
					if (options.itemType === 'commands') {
						atts.autofocus = 'autofocus';
					}
					return atts;
				}(options))]
			]]
		]],
		['table', [
			/*
			['tr', [
				['td', [
					['label', [_("Label:")]]
				]],
				['td', [
					['input', {id: 'label'}]
				]]
			]]
			*/
			['tr', [
				['td', [
					['label', {'for': 'executablePath'}, [_("Path of executable")]]
				]],
				['td', [
					['select', {id: 'executables', 'class': 'ei-exe-presets', dataset: {sel: '#executablePath'}}],
					['input', (function (options) {
						var atts = {type: 'text', size: '55', id: 'executablePath', 'class': 'ei-exe-path', list: 'datalist', autocomplete: 'off', value: '', required:'required'};
						if (options.itemType === 'one-off') {
							atts.autofocus = 'autofocus';
						}
						return atts;
					}(options))],
					['input', {type: 'button', id: 'executablePick', 'class': 'ei-exe-picker', dataset: {sel: '#executablePath', 'default-extension': 'exe'}, value: _("Browse")}],
					['datalist', {id: 'datalist'}],
					['input', {type: 'button', 'class': 'ei-exe-revealButton', dataset: {sel: '#executablePath'}}]
				]]
			]]
		]],
		['div', {id: 'executableTableContainer'}, [
			['table', {id: 'executableTable'}]
		]],
		['div', {id: 'fileAndURLArgumentContainer'}, [
			['b', [_("Hard-coded files and URLs")]],
			['br'],
			['table', {id: 'fileArguments'}],
			['table', {id: 'URLArguments'}]
		]],
		['br'],
		['div', {'class': 'focus'}, [
			/*
			['button', {id: 'saveAndExecute'}, [_("Save and execute")]],
			['button', {id: 'saveAndClose'}, [_("Save and close")]]
			['br'],
			['br']
			*/
			['label', [_("keep_dialog_open"), ['input', {type: 'checkbox', id: 'keepOpen'}]]],
			['br'],
			['button', {id: 'execute'}, [_("Execute")]],
			['button', {id: 'cancel'}, [_("Cancel")]]
		]]
	]]
], $('body'));

$('body').addEventListener('click', function (e) {
	var val, sel, selVal,
		target = e.target,
		dataset = target.dataset || {},
		cl = target.classList;
	function getValues (type, expInput) {
		var selector = '.' + expInput.getPrefixedNamespace() + type;
		return Array.from($$(selector)).map(function (arg) {
			if (arg.type === 'checkbox') {
				return arg.checked;
			}
			return arg.value;
		});
	}
	function getInputValues (expInput) {
		return getValues('input', expInput);
	}

	if (cl.contains('ei-files-presets') || (target.parentNode && target.parentNode.classList.contains('ei-files-presets')) ||
		cl.contains('ei-exe-presets') || (target.parentNode && target.parentNode.classList.contains('ei-exe-presets'))) {
		val = target.value;
		if (!val) {
			return;
		}
		sel = dataset.sel || (target.parentNode && target.parentNode.dataset.sel);
		if (sel) {
			$(sel).value = val;
		}
	}
	else if (cl.contains('ei-files-picker') || cl.contains('ei-exe-picker')) {
		sel = dataset.sel;
		emit('filePick', {
			dirPath: $(sel).value,
			selector: sel,
			defaultExtension: dataset.defaultExtension || undefined,
			selectFolder: ($(dataset.directory) && $(dataset.directory).checked) ? true : undefined
		});
	}
	else if (cl.contains('ei-files-revealButton') || cl.contains('ei-exe-revealButton')) {
		sel = dataset.sel;
		selVal = sel && $(sel).value;
		if (selVal) {
			emit('reveal', selVal);
		}
	}
	// Abstract this
	else if (cl.contains(files.getPrefixedNamespace() + 'add')) {
		files.add();
	}
	else if (cl.contains(files.getPrefixedNamespace() + 'remove')) {
		files.remove(dataset.id);
	}
	else if (cl.contains(urls.getPrefixedNamespace() + 'add')) {
		urls.add();
	}
	else if (cl.contains(urls.getPrefixedNamespace() + 'remove')) {
		urls.remove(dataset.id);
	}
	else if (cl.contains(args.getPrefixedNamespace() + 'add')) {
		args.add();
	}
	else if (cl.contains(args.getPrefixedNamespace() + 'remove')) {
		args.remove(dataset.id);
	}
	else if (target.id === 'cancel') {
		emit('buttonClick', {id: 'cancel'});
	}
	else if (target.id === 'execute') {
		emit('buttonClick', {
			id: target.id,
			executablePath: $('#executablePath').value,
			args: getInputValues(args),
			files: getInputValues(files),
			urls: getInputValues(urls),
			dirs: getValues('directory', files)
		});
	}
});

$('body').addEventListener('input', function (e) {
	var target = e.target, val = e.target.value;
	if (target.classList.contains('ei-files-path') || target.classList.contains('ei-exe-path')) {
		emit('autocompleteValues', {
			value: val,
			listID: target.getAttribute('list')
		});
	}
});

// COPIED FROM filebrowser-enhanced directoryMod.js (RETURN ALL MODIFICATIONS THERE)
on('autocompleteValuesResponse', function (data) {
	var datalist = document.getElementById(data.listID);
	while (datalist.firstChild) {
		datalist.removeChild(datalist.firstChild);
	}
	data.optValues.forEach(function (optValue) {
		var option = jml('option', {
			// text: optValue,
			value: optValue
		});
		datalist.appendChild(option);
	});
});

on('finished', function () {
	$('#processExecuted').style.visibility = 'visible';
	if (!$('#keepOpen').checked) {
		emit('buttonClick', {id: 'cancel'});
	}
	else {
		setTimeout(function () {
			$('#processExecuted').style.visibility = 'hidden';
		}, 2000);
	}
});

function fileOrDirResult (data) {
	var path = data.path,
		selector = data.selector;
	if (path) {
		$(selector).value = path;
	}
}
on('filePickResult', fileOrDirResult);

// SETUP

// Insert this as a class, so it works for others inserted into doc
$('#dynamicStyleRules').sheet.insertRule(
	'.ei-files-revealButton, .ei-exe-revealButton {background-image: url("' + options.folderImage + '");}', 0
);

function handleOptions (data) {
	var paths = data.paths,
		type = data.type,
		sel = type === 'executables' ? '#' + type : '.ei-files-presets';

	paths.forEach(function (pathInfo) {
		var option = document.createElement('option');
		option.text = pathInfo[0];
		option.value = pathInfo[1];
		$(sel).appendChild(option);
	});
}
on('executables', handleOptions);
on('temps', handleOptions);

// Todo: For prefs when prev. values stored, call multiple times and populate
args.add();
urls.add();
files.add();

}());
<commit_msg>selected by default<commit_after>/*globals ExpandableInputs, self, jml */
/*jslint todo:true*/
(function () {'use strict';

var
	emit = self.port.emit,
	on = self.port.on,
	options = self.options,
	locale = options.locale,
	ei_locale = options.ei_locale,
	args = new ExpandableInputs({
		locale: ei_locale,
		table: 'executableTable',
		namespace: 'args',
		label: ei_locale.args_num,
		inputSize: 60,
		rows: 1 // Might perhaps make this optional to save space, but this triggers creation of a textarea so args could be more readable (since to auto-escape newlines as needed)
	}),
	urls = new ExpandableInputs({
		locale: ei_locale,
		table: 'URLArguments',
		namespace: 'urls',
		label: ei_locale.url_num,
		inputSize: 40,
		inputType: 'url'
	}),
	files = new ExpandableInputs({
		locale: ei_locale,
		table: 'fileArguments',
		namespace: 'files',
		label: ei_locale.file_num,
		inputSize: 25,
		inputType: 'file',
		selects: true
	});

// POLYFILLS
Array.from = function (arg) {
	return [].slice.call(arg);
};

// UTILITIES
function l (msg) {
	console.log(msg);
}
function $ (sel) {
	return document.querySelector(sel);
}
function $$ (sel) {
	return document.querySelectorAll(sel);
}
function forSel (sel, cb) {
	Array.from($$(sel)).forEach(cb);
}
function _ (key) {
	return locale[key] || '(Non-internationalized string--FIXME!)' + key;
}

// ADD EVENTS

document.title = _("title");
jml('div', [
	['div', (function (options) {
		var atts = {id: 'names'};
		if (options.itemType === 'one-off') {
			atts.hidden = true;
		}
		return atts;
	}(options)), [
		['select', {id: 'selectNames', size: 50, $on: {click: function (e) {
			if (e.target.nodeName.toLowerCase() !== 'option') {
				return;
			}
			if (e.target.value === '') { // Create new command

			}
			else {

			}
		}}}, [
			['option', {value: '', selected: 'selected'}, [_("create_new_command")]],
			['option', ['Name2']]
		]]
	]],
	['div', (function (options) {
		var atts = {id: 'main'};
		atts.className = options.itemType === 'one-off' ? 'closed' : 'open';
		return atts;
	}(options)), [
		['button', {id: 'showNames', $on: {click: function () {
			$('#names').hidden = !$('#names').hidden;
			var showNames = $('#showNames');
			if (!$('#names').hidden) {
				$('#main').className = 'open';
				showNames.replaceChild(document.createTextNode(_("lt")), showNames.firstChild);
			}
			else {
				$('#main').className = 'closed';
				showNames.replaceChild(document.createTextNode(_("gt")), showNames.firstChild);
			}
		}}}, [
			_(options.itemType === 'one-off' ? "gt" : "lt")
		]],
		['div', {id: 'processExecuted', style: 'visibility:hidden;'}, [
			_("Process executed")
		]],
		['div', {id: 'substitutions-explanation-container'}, [
			['h3', [_("Substitutions explained")]],
			['div', {id: 'substitutions-explanation'}, [
				_("Substitution_sequences_allow"),
				['br'],['br'],
				_("prefixes_can_be_applied"),
				['dl', [
						'save-temp', 'ucencode-', 'uencode-', 'escquotes-'
					].reduce(function (children, prefix) {
						children.push(['dt', [prefix]]);
						children.push(['dd', [_("prefix_" + prefix)]]);
						return children;
					}, [])
				],
				['b', [_("Sequences")]],
				['dl', [
						'eval', 'pageURL', 'pageTitle', 'pageHTML', 'bodyText',
						'selectedHTML', 'selectedText', 'linkPageURL',
						'linkPageURLAsNativePath', 'linkPageTitle',
						'linkBodyText', 'linkPageHTML', 'imageURL',
						'imageDataURL', 'imageDataBinary'
					].reduce(function (children, seq) {
						children.push(['dt', [seq]]);
						children.push(['dd', [_("seq_" + seq)]]);
						return children;
					}, [])
				]
			]]
		]],
		['div', {id: 'substitutions-used-container'}, [
			['h3', [_("Substitutions used")]],
			['div', {id: 'substitutions-used'}, [
				_("currently_available_sequences"),
				['br'],['br'],
				/*
				['dl', [
					['dt', ['save-temp-']], ['dd'],
					['dt', ['ucencode-']], ['dd'],
					['dt', ['uencode-']], ['dd'],
					['dt', ['escquotes-']], ['dd'],
				]],
				*/
				['b', [_("Sequences")]],
				['dl', [
						'eval', 'pageURL', 'pageTitle', 'pageHTML', 'bodyText',
						'selectedHTML', 'selectedText', 'linkPageURL',
						'linkPageURLAsNativePath', 'linkPageTitle',
						'linkBodyText', 'linkPageHTML', 'imageURL',
						'imageDataURL', 'imageDataBinary'
					].reduce(function (children, seq) {
						children.push(['dt', [seq]]);
						children.push(['dd']);
						return children;
					}, [])
				]
			]]
		]],
		['div', {id: 'command-name-section'}, [
			['label', {title: _("if_present_command_saved")}, [
				_("Command name") + ' ',
				['input', (function (options) {
					var atts = {id: 'command-name', size: '55'};
					if (options.itemType === 'commands') {
						atts.autofocus = 'autofocus';
					}
					return atts;
				}(options))]
			]]
		]],
		['table', [
			/*
			['tr', [
				['td', [
					['label', [_("Label:")]]
				]],
				['td', [
					['input', {id: 'label'}]
				]]
			]]
			*/
			['tr', [
				['td', [
					['label', {'for': 'executablePath'}, [_("Path of executable")]]
				]],
				['td', [
					['select', {id: 'executables', 'class': 'ei-exe-presets', dataset: {sel: '#executablePath'}}],
					['input', (function (options) {
						var atts = {type: 'text', size: '55', id: 'executablePath', 'class': 'ei-exe-path', list: 'datalist', autocomplete: 'off', value: '', required:'required'};
						if (options.itemType === 'one-off') {
							atts.autofocus = 'autofocus';
						}
						return atts;
					}(options))],
					['input', {type: 'button', id: 'executablePick', 'class': 'ei-exe-picker', dataset: {sel: '#executablePath', 'default-extension': 'exe'}, value: _("Browse")}],
					['datalist', {id: 'datalist'}],
					['input', {type: 'button', 'class': 'ei-exe-revealButton', dataset: {sel: '#executablePath'}}]
				]]
			]]
		]],
		['div', {id: 'executableTableContainer'}, [
			['table', {id: 'executableTable'}]
		]],
		['div', {id: 'fileAndURLArgumentContainer'}, [
			['b', [_("Hard-coded files and URLs")]],
			['br'],
			['table', {id: 'fileArguments'}],
			['table', {id: 'URLArguments'}]
		]],
		['br'],
		['div', {'class': 'focus'}, [
			/*
			['button', {id: 'saveAndExecute'}, [_("Save and execute")]],
			['button', {id: 'saveAndClose'}, [_("Save and close")]]
			['br'],
			['br']
			*/
			['label', [_("keep_dialog_open"), ['input', {type: 'checkbox', id: 'keepOpen'}]]],
			['br'],
			['button', {id: 'execute'}, [_("Execute")]],
			['button', {id: 'cancel'}, [_("Cancel")]]
		]]
	]]
], $('body'));

$('body').addEventListener('click', function (e) {
	var val, sel, selVal,
		target = e.target,
		dataset = target.dataset || {},
		cl = target.classList;
	function getValues (type, expInput) {
		var selector = '.' + expInput.getPrefixedNamespace() + type;
		return Array.from($$(selector)).map(function (arg) {
			if (arg.type === 'checkbox') {
				return arg.checked;
			}
			return arg.value;
		});
	}
	function getInputValues (expInput) {
		return getValues('input', expInput);
	}

	if (cl.contains('ei-files-presets') || (target.parentNode && target.parentNode.classList.contains('ei-files-presets')) ||
		cl.contains('ei-exe-presets') || (target.parentNode && target.parentNode.classList.contains('ei-exe-presets'))) {
		val = target.value;
		if (!val) {
			return;
		}
		sel = dataset.sel || (target.parentNode && target.parentNode.dataset.sel);
		if (sel) {
			$(sel).value = val;
		}
	}
	else if (cl.contains('ei-files-picker') || cl.contains('ei-exe-picker')) {
		sel = dataset.sel;
		emit('filePick', {
			dirPath: $(sel).value,
			selector: sel,
			defaultExtension: dataset.defaultExtension || undefined,
			selectFolder: ($(dataset.directory) && $(dataset.directory).checked) ? true : undefined
		});
	}
	else if (cl.contains('ei-files-revealButton') || cl.contains('ei-exe-revealButton')) {
		sel = dataset.sel;
		selVal = sel && $(sel).value;
		if (selVal) {
			emit('reveal', selVal);
		}
	}
	// Abstract this
	else if (cl.contains(files.getPrefixedNamespace() + 'add')) {
		files.add();
	}
	else if (cl.contains(files.getPrefixedNamespace() + 'remove')) {
		files.remove(dataset.id);
	}
	else if (cl.contains(urls.getPrefixedNamespace() + 'add')) {
		urls.add();
	}
	else if (cl.contains(urls.getPrefixedNamespace() + 'remove')) {
		urls.remove(dataset.id);
	}
	else if (cl.contains(args.getPrefixedNamespace() + 'add')) {
		args.add();
	}
	else if (cl.contains(args.getPrefixedNamespace() + 'remove')) {
		args.remove(dataset.id);
	}
	else if (target.id === 'cancel') {
		emit('buttonClick', {id: target.id});
	}
	else if (target.id === 'execute') {
		emit('buttonClick', {
			id: target.id,
			executablePath: $('#executablePath').value,
			args: getInputValues(args),
			files: getInputValues(files),
			urls: getInputValues(urls),
			dirs: getValues('directory', files)
		});
	}
});

$('body').addEventListener('input', function (e) {
	var target = e.target, val = e.target.value;
	if (target.classList.contains('ei-files-path') || target.classList.contains('ei-exe-path')) {
		emit('autocompleteValues', {
			value: val,
			listID: target.getAttribute('list')
		});
	}
});

// COPIED FROM filebrowser-enhanced directoryMod.js (RETURN ALL MODIFICATIONS THERE)
on('autocompleteValuesResponse', function (data) {
	var datalist = document.getElementById(data.listID);
	while (datalist.firstChild) {
		datalist.removeChild(datalist.firstChild);
	}
	data.optValues.forEach(function (optValue) {
		var option = jml('option', {
			// text: optValue,
			value: optValue
		});
		datalist.appendChild(option);
	});
});

on('finished', function () {
	$('#processExecuted').style.visibility = 'visible';
	if (!$('#keepOpen').checked) {
		emit('buttonClick', {id: 'cancel'});
	}
	else {
		setTimeout(function () {
			$('#processExecuted').style.visibility = 'hidden';
		}, 2000);
	}
});

function fileOrDirResult (data) {
	var path = data.path,
		selector = data.selector;
	if (path) {
		$(selector).value = path;
	}
}
on('filePickResult', fileOrDirResult);

// SETUP

// Insert this as a class, so it works for others inserted into doc
$('#dynamicStyleRules').sheet.insertRule(
	'.ei-files-revealButton, .ei-exe-revealButton {background-image: url("' + options.folderImage + '");}', 0
);

function handleOptions (data) {
	var paths = data.paths,
		type = data.type,
		sel = type === 'executables' ? '#' + type : '.ei-files-presets';

	paths.forEach(function (pathInfo) {
		var option = document.createElement('option');
		option.text = pathInfo[0];
		option.value = pathInfo[1];
		$(sel).appendChild(option);
	});
}
on('executables', handleOptions);
on('temps', handleOptions);

// Todo: For prefs when prev. values stored, call multiple times and populate
args.add();
urls.add();
files.add();

}());
<|endoftext|>


<commit_before>var wrapPatterns = {};

function makeWrapRx(width) {
  var withspace = '((?:(?:<.*?>)?(?:[^<>&]|&.*?;)(?:<.*?>)?){0,' + width + '})(?: |\\s+)';
  var nospace = '((?:(?:<.*?>)?(?:[^<>&]|&.*?;)(?:<.*?>)?){' + width + '})';
  var end = '((?:(?:<.*?>)?(?:[^<>&]|&.*?;)(?:<.*?>)?){1,' + width + '})\s*$';
  var rx = end + '|' + withspace + '|' + nospace;
  return new RegExp(rx,'g');
}

function wrapLines(lines,width) {
  var newlines = [];
  var rx;
  var nlines = lines.length;
  rx = wrapPatterns[width];
  if (rx == undefined) {
    rx = makeWrapRx(width);
    wrapPatterns[width] = rx;
  }
  for (var i = 0; i < nlines; i += 1) {
    var line = lines[i];
    var newline = '' + line;
    newline = newline.replace(rx,function(str,end,withspace,nospace) {
      if (withspace) {
        newlines.push(withspace);
      } else if (nospace) {
        newlines.push(nospace);
      } else if (end) {
        newlines.push(end);
      } else {
        newlines.push(str);
      }
    });
  };
  return newlines;
}
<commit_msg>wrapLines now no longer ignores empty lines.<commit_after>var wrapPatterns = {};

function makeWrapRx(width) {
  var withspace = '((?:(?:<.*?>)?(?:[^<>&]|&.*?;)(?:<.*?>)?){0,' + width + '})(?: |\\s+)';
  var nospace = '((?:(?:<.*?>)?(?:[^<>&]|&.*?;)(?:<.*?>)?){' + width + '})';
  var end = '((?:(?:<.*?>)?(?:[^<>&]|&.*?;)(?:<.*?>)?){1,' + width + '})\s*$';
  var rx = end + '|' + withspace + '|' + nospace;
  return new RegExp(rx,'g');
}

function wrapLines(lines,width) {
  var newlines = [];
  var rx;
  var nlines = lines.length;
  rx = wrapPatterns[width];
  if (rx == undefined) {
    rx = makeWrapRx(width);
    wrapPatterns[width] = rx;
  }
  for (var i = 0; i < nlines; i += 1) {
    var line = lines[i] || '';
    var newline = '' + line;
    if (newline == '') {
      newlines.push('');
    } else {
      newline = newline.replace(rx,function(str,end,withspace,nospace) {
        if (withspace) {
          newlines.push(withspace);
        } else if (nospace) {
          newlines.push(nospace);
        } else if (end) {
          newlines.push(end);
        } else {
          newlines.push(str);
        }
      });
    }
  };
  return newlines;
}
<|endoftext|>


<commit_before>function addSkill() {
  $("#new_skill").on("submit", function (event) {
    event.preventDefault();
    var $target = $(event.target);
    if ($('#skill_title').val() === "") {
      alert("No skill specified");
    } else {
      $.ajax({
        url: $target.attr("action") + '.json',
        type: "post",
        data: $target.serialize()
      }).done(function (response) {
        $('.vertical-tabs').append(formatVerticalTabs(response))
        $('.vertical-tabs').animate({ scrollTop: $(document).height() }, "slow");
        $target[0][2].value = "";
      });
    }
  });
}

function formatVerticalTabs (skill) {
  return "" + skill.title + "";
}

// function formatVerticalTabsContentLink (skill) {
//   return "" + skill.title + "";
// }

// function formatVerticalTabsContentDiv (skill) {
//   return <div id="<%= skill.title.gsub(" ", "-") %>" class="js-vertical-tab-content vertical-tab-content">
//           <%= "Current streak: " + skill.current_streak.to_s %>

//           <%= "Longest streak: " + skill.longest_streak.to_s %>

//           ;
// }<commit_msg>whitespace<commit_after>function addSkill() {
  $("#new_skill").on("submit", function (event) {
    event.preventDefault();
    var $target = $(event.target);
    if ($('#skill_title').val() === "") {
      alert("No skill specified");
    } else {
      $.ajax({
        url: $target.attr("action") + '.json',
        type: "post",
        data: $target.serialize()
      }).done(function (response) {
        $('.vertical-tabs').append(formatVerticalTabs(response));
        $('.vertical-tab-content-container').append(formatVerticalTabsContentLink(response));
        $('.skills').append(formatVerticalTabsContentDiv(response));
        $("a[rel=" + response.id.toString() + "]").click();
        $('.vertical-tabs').animate({ scrollTop: $(document).height() }, "slow");
        $target[0][2].value = "";
        countdown();
      });
    }
  });
}

function formatCurrentDateTime(date){
  var year = date.getFullYear().toString();
  var month = (date.getMonth() + 1).toString();
  var day = (date.getDate() + 1).toString();
  var hours = date.getHours().toString();
  var minutes = date.getMinutes().toString();
  var seconds = date.getSeconds().toString();

  if (parseInt(month, 10) < 10) {
    month = "0" + month
  }

  if (parseInt(day, 10) < 10) {
    day = "0" + day
  }

  if (parseInt(hours, 10) < 10) {
    hours = "0" + hours
  }

  if (parseInt(minutes, 10) < 10) {
    minutes = "0" + minutes
  }

  if (parseInt(seconds, 10) < 10) {
    seconds = "0" + seconds
  }

  return year + "/" + month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
}

function formatVerticalTabs (skill) {
  return "" + skill.title + "";
}

function formatVerticalTabsContentLink (skill) {
  return "" + skill.title + "";
}

function formatVerticalTabsContentDiv (skill) {
  var date = new Date;
  return "
" +
            "Current streak: " + skill.current_streak.toString() + "

" +
            "Longest streak: " + skill.longest_streak.toString() + "

" +
            "
";
}

<|endoftext|>


<commit_before>(function(global) {
    'use strict';
    var GOVUK = global.GOVUK || {};
    var $ = global.jQuery;

    function generateEightHexadecimalDigits() {
        return Math.random().toString(16).substr(2, 8);
    }

    function getPiwikVisitorIdCookie() {
        var userId = GOVUK.getCookie('PIWIK_USER_ID');
        if (!userId) {
            userId = generateEightHexadecimalDigits() + generateEightHexadecimalDigits();
            GOVUK.setCookie('PIWIK_USER_ID', userId);
        }
        return userId;
    }

    var trackerUrl = $('#piwik-url').text();

    if(!trackerUrl) {
        return;
    }

    var siteId = $('#piwik-site-id').text();
    var customUrl = $('#piwik-custom-url').text();
    var enTitle = $('meta[name="verify|title"]').attr("content");
    var newVisit = $('#piwik-new-visit')

    if(newVisit.length) {
        var newVisitFlag = 1;
        // to make sure the new visit flag is used only once
        newVisit.remove();
    }
    else {
        var newVisitFlag = 0;
    }

    var piwikAnalyticsQueue = [
        ['appendToTrackingUrl', 'new_visit=' + newVisitFlag],
        ['setUserId', getPiwikVisitorIdCookie()],
        ['setDocumentTitle', enTitle ],
        ['trackPageView'],
        ['enableLinkTracking'],
        ['setTrackerUrl', trackerUrl],
        ['setSiteId', siteId]
    ];

    var customVariablesString = $('#piwik-custom-variables').text();
    if (customVariablesString) {
        var customVariables = JSON.parse(customVariablesString);
        $.each(customVariables, function(index) {
            piwikAnalyticsQueue.unshift([
                'setCustomVariable',
                customVariables[index].index,
                customVariables[index].name,
                customVariables[index].value,
                customVariables[index].scope
            ])
        });
    }

    if (customUrl) {
        // customUrl needs to go at the beginning of the piwik array
        piwikAnalyticsQueue.unshift(['setCustomUrl', customUrl]);
    }

    global._paq = piwikAnalyticsQueue;
})(window);
<commit_msg>HUB-113: Codacy styling fixes<commit_after>(function(global) {
    'use strict';
    var GOVUK = global.GOVUK || {};
    var $ = global.jQuery;

    function generateEightHexadecimalDigits() {
        return Math.random().toString(16).substr(2, 8);
    }

    function getPiwikVisitorIdCookie() {
        var userId = GOVUK.getCookie('PIWIK_USER_ID');
        if (!userId) {
            userId = generateEightHexadecimalDigits() + generateEightHexadecimalDigits();
            GOVUK.setCookie('PIWIK_USER_ID', userId);
        }
        return userId;
    }

    var trackerUrl = $('#piwik-url').text();

    if(!trackerUrl) {
        return;
    }

    var siteId = $('#piwik-site-id').text();
    var customUrl = $('#piwik-custom-url').text();
    var enTitle = $('meta[name="verify|title"]').attr("content");
    var newVisit = $('#piwik-new-visit');

    var newVisitFlag = 0;
    if(newVisit.length) {
        newVisitFlag = 1;
        // to make sure the new visit flag is used only once
        newVisit.remove();
    }

    var piwikAnalyticsQueue = [
        ['appendToTrackingUrl', 'new_visit=' + newVisitFlag],
        ['setUserId', getPiwikVisitorIdCookie()],
        ['setDocumentTitle', enTitle ],
        ['trackPageView'],
        ['enableLinkTracking'],
        ['setTrackerUrl', trackerUrl],
        ['setSiteId', siteId]
    ];

    var customVariablesString = $('#piwik-custom-variables').text();
    if (customVariablesString) {
        var customVariables = JSON.parse(customVariablesString);
        $.each(customVariables, function(index) {
            piwikAnalyticsQueue.unshift([
                'setCustomVariable',
                customVariables[index].index,
                customVariables[index].name,
                customVariables[index].value,
                customVariables[index].scope
            ])
        });
    }

    if (customUrl) {
        // customUrl needs to go at the beginning of the piwik array
        piwikAnalyticsQueue.unshift(['setCustomUrl', customUrl]);
    }

    global._paq = piwikAnalyticsQueue;
})(window);
<|endoftext|>


<commit_before>(function () {
   'use strict';
    var trackerUrl = $('#piwik-url').text();
    if(!trackerUrl) {
        return;
    }
    var siteId = $('#piwik-site-id').text();
    var customUrl = $('#piwik-custom-url').text();
    var _paq = [];
    _paq.push(['setDocumentTitle', document.title ]);
    if(customUrl) {
        _paq.push(['setCustomUrl', customUrl]);
    }
    _paq.push(["trackPageView"]);
    _paq.push(["enableLinkTracking"]);
    _paq.push([ function() {
        var visitor_id = this.getVisitorId();
        GOVUK.setCookie("PIWIK_VISITOR_ID", visitor_id);
    }]);
    _paq.push(["setTrackerUrl", trackerUrl]);
    _paq.push(["setSiteId", siteId]);
    window._paq = _paq;
})();
<commit_msg>3470: Refactor analytics JS for clarity<commit_after>(function () {
   'use strict';

    function setPiwikVisitorIdCookie () {
        var visitor_id = this.getVisitorId();
        GOVUK.setCookie('PIWIK_VISITOR_ID', visitor_id);
    }

    var trackerUrl = $('#piwik-url').text(),
        siteId,
        customUrl,
        piwikAnalyticsQueue;

    if(!trackerUrl) {
        return;
    }

    siteId = $('#piwik-site-id').text();
    customUrl = $('#piwik-custom-url').text();

    piwikAnalyticsQueue = [
      ['setDocumentTitle', document.title ],
      ['trackPageView'],
      ['enableLinkTracking'],
      [setPiwikVisitorIdCookie],
      ['setTrackerUrl', trackerUrl],
      ['setSiteId', siteId]
    ];

    if (customUrl) {
      // customUrl needs to go at the beginning of the piwik array
      piwikAnalyticsQueue.unshift(['setCustomUrl', customUrl]);
    }

    window._paq = piwikAnalyticsQueue;
})();
<|endoftext|>


<commit_before>//= require application
//= require refresh
//= require twitter
//= require versionCheck
//= require projectCheck
//= require spin

$(function() {
  VersionCheck.init();
  ProjectCheck.init();
  var projectsCount = $("body").projectsCount();
  $('.building-indicator').setSpinner(projectsCount);
});

$.fn.projectsCount = function(){
  return parseInt($(this).data("tiles-count"));
};

$.fn.setSpinner = function(projectsCount){
  var $this = $(this);

  if (projectsCount == 15) {
    $this.spin({radius:8, length:9, width:3, lines:12, top:2, left:16});
  }
  else if (projectsCount == 24) {
    $this.spin({radius:6, length:7, width:2, lines:12, top:4, left:6});
  }
  else if (projectsCount == 63) {
    $this.spin({radius:4, length:4, width:1, lines:12, top:3, left:12});
  }
  else {
    $this.spin({radius:4, length:6, width:1, lines:12, top:1, left:10});
  }
};

$.fn.spin = function(opts) {
  this.each(function() {
    var $this = $(this),
        data = $this.data();

    if (data.spinner) {
      data.spinner.stop();
      delete data.spinner;
    }
    if (opts !== false) {
      data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
    }
  });
  return this;
};
<commit_msg>Fix JSlint parseInt bug<commit_after>//= require application
//= require refresh
//= require twitter
//= require versionCheck
//= require projectCheck
//= require spin

$(function() {
  VersionCheck.init();
  ProjectCheck.init();
  var projectsCount = $("body").projectsCount();
  $('.building-indicator').setSpinner(projectsCount);
});

$.fn.projectsCount = function(){
  return parseInt($(this).data("tiles-count"), 10);
};

$.fn.setSpinner = function(projectsCount){
  var $this = $(this);

  if (projectsCount == 15) {
    $this.spin({radius:8, length:9, width:3, lines:12, top:2, left:16});
  }
  else if (projectsCount == 24) {
    $this.spin({radius:6, length:7, width:2, lines:12, top:4, left:6});
  }
  else if (projectsCount == 63) {
    $this.spin({radius:4, length:4, width:1, lines:12, top:3, left:12});
  }
  else {
    $this.spin({radius:4, length:6, width:1, lines:12, top:1, left:10});
  }
};

$.fn.spin = function(opts) {
  this.each(function() {
    var $this = $(this),
        data = $this.data();

    if (data.spinner) {
      data.spinner.stop();
      delete data.spinner;
    }
    if (opts !== false) {
      data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
    }
  });
  return this;
};
<|endoftext|>


<commit_before>import { app, ipcMain } from 'electron'
import sqlite3 from 'sqlite3'
import path from 'path'
import url from 'url'
import rpc from 'pauls-electron-rpc'
import manifest from './api-manifests/bookmarks'
import * as pluginModules from './plugin-modules'
import { setupDatabase } from '../lib/bg/sqlite-tools'
import log from '../log'

// globals
// =
var db
var migrations
var waitForSetup

// exported methods
// =

export function setup () {
  // open database
  var dbPath = path.join(app.getPath('userData'), 'Bookmarks')
  db = new sqlite3.Database(dbPath)
  waitForSetup = setupDatabase(db, migrations, '[BOOKMARKS]')

  // wire up RPC
  rpc.exportAPI('beakerBookmarks', manifest, { add, changeTitle, changeUrl, addVisit, remove, get, list })
}

export function add (url, title, cb) {
  waitForSetup(() => {
    db.run(`
      INSERT OR REPLACE
        INTO bookmarks (url, title, num_visits)
        VALUES (?, ?, 0)
    `, [url, title], cb)
  })
}

export function changeTitle (url, title, cb) {
  waitForSetup(() => {
    db.run(`UPDATE bookmarks SET title = ? WHERE url = ?`, [title, url], cb)
  })
}

export function changeUrl (oldUrl, newUrl, cb) {
  waitForSetup(() => {
    db.run(`UPDATE bookmarks SET url = ? WHERE url = ?`, [newUrl, oldUrl], cb)
  })
}

export function addVisit (url, cb) {
  waitForSetup(() => {
    db.run(`UPDATE bookmarks SET num_visits = num_visits + 1 WHERE url = ?`, url, cb)
  })
}

export function remove (url, cb) {
  waitForSetup(() => {
    db.run(`DELETE FROM bookmarks WHERE url = ?`, [url], cb)
  })
}

export function get (url, cb) {
  waitForSetup(() => {
    db.get(`SELECT url, title FROM bookmarks WHERE url = ?`, [url], cb)
  })
}

export function list (cb) {
  waitForSetup(() => {
    db.all(`SELECT url, title FROM bookmarks ORDER BY num_visits DESC`, cb)
  })
}

// internal methods
// =

migrations = [
  // version 1
  function (cb) {
    db.exec(`
      CREATE TABLE bookmarks(
        url NOT NULL,
        title
      );
      CREATE INDEX bookmarks_url ON bookmarks (url);
      INSERT INTO bookmarks (title, url) VALUES ('Beaker Browser Homepage', 'https://github.com/pfrazee/beaker');
      INSERT INTO bookmarks (title, url) VALUES ('@pfrazee - Twitter', 'https://twitter.com/pfrazee');
      INSERT INTO bookmarks (title, url) VALUES ('Dat Protocol', 'http://dat-data.com/');
      INSERT INTO bookmarks (title, url) VALUES ('DuckDuckGo (the default search engine)', 'https://duckduckgo.com');
      PRAGMA user_version = 1;
    `, cb)
  },
  // version 2
  function (cb) {
    db.exec(`
      ALTER TABLE bookmarks ADD COLUMN num_visits;
      UPDATE bookmarks SET num_visits = 0;
      PRAGMA user_version = 2;
    `, cb)
  }
]<commit_msg>add IPFS links to default bookmarks<commit_after>import { app, ipcMain } from 'electron'
import sqlite3 from 'sqlite3'
import path from 'path'
import url from 'url'
import rpc from 'pauls-electron-rpc'
import manifest from './api-manifests/bookmarks'
import * as pluginModules from './plugin-modules'
import { setupDatabase } from '../lib/bg/sqlite-tools'
import log from '../log'

// globals
// =
var db
var migrations
var waitForSetup

// exported methods
// =

export function setup () {
  // open database
  var dbPath = path.join(app.getPath('userData'), 'Bookmarks')
  db = new sqlite3.Database(dbPath)
  waitForSetup = setupDatabase(db, migrations, '[BOOKMARKS]')

  // wire up RPC
  rpc.exportAPI('beakerBookmarks', manifest, { add, changeTitle, changeUrl, addVisit, remove, get, list })
}

export function add (url, title, cb) {
  waitForSetup(() => {
    db.run(`
      INSERT OR REPLACE
        INTO bookmarks (url, title, num_visits)
        VALUES (?, ?, 0)
    `, [url, title], cb)
  })
}

export function changeTitle (url, title, cb) {
  waitForSetup(() => {
    db.run(`UPDATE bookmarks SET title = ? WHERE url = ?`, [title, url], cb)
  })
}

export function changeUrl (oldUrl, newUrl, cb) {
  waitForSetup(() => {
    db.run(`UPDATE bookmarks SET url = ? WHERE url = ?`, [newUrl, oldUrl], cb)
  })
}

export function addVisit (url, cb) {
  waitForSetup(() => {
    db.run(`UPDATE bookmarks SET num_visits = num_visits + 1 WHERE url = ?`, url, cb)
  })
}

export function remove (url, cb) {
  waitForSetup(() => {
    db.run(`DELETE FROM bookmarks WHERE url = ?`, [url], cb)
  })
}

export function get (url, cb) {
  waitForSetup(() => {
    db.get(`SELECT url, title FROM bookmarks WHERE url = ?`, [url], cb)
  })
}

export function list (cb) {
  waitForSetup(() => {
    db.all(`SELECT url, title FROM bookmarks ORDER BY num_visits DESC`, cb)
  })
}

// internal methods
// =

migrations = [
  // version 1
  function (cb) {
    db.exec(`
      CREATE TABLE bookmarks(
        url NOT NULL,
        title
      );
      CREATE INDEX bookmarks_url ON bookmarks (url);
      INSERT INTO bookmarks (title, url) VALUES ('Beaker Browser Homepage', 'https://github.com/pfrazee/beaker');
      INSERT INTO bookmarks (title, url) VALUES ('Dat Protocol', 'http://dat-data.com/');
      INSERT INTO bookmarks (title, url) VALUES ('IPFS Protocol', 'https://ipfs.io');
      INSERT INTO bookmarks (title, url) VALUES ('DuckDuckGo (the default search engine)', 'https://duckduckgo.com');
      INSERT INTO bookmarks (title, url) VALUES ('Some IPFS Links', 'ipfs:/ipfs/QmU5XsVwvJfTcCwqkK1SmTqDmXWSQWaTa7ZcVLY2PDxNxG/ipfs_links.html');
      PRAGMA user_version = 1;
    `, cb)
  },
  // version 2
  function (cb) {
    db.exec(`
      ALTER TABLE bookmarks ADD COLUMN num_visits;
      UPDATE bookmarks SET num_visits = 0;
      PRAGMA user_version = 2;
    `, cb)
  }
]<|endoftext|>