<commit_before>

var buoys_layer;
var single_marker_layer;
var user_marker = {};
var mode=null;
$(document).ready(function() {

    function create_buoys_plane(){
        var buoys_plane = [];
        $('.buoy').each(function(i, obj) {
            var buoy_id = $(this).data("id");
            var buoy_lat = $(this).data("lat");
            var buoy_lon = $(this).data("lon");
            var buoy = [buoy_id, buoy_lat, buoy_lon];
            buoys_plane.push(buoy);
        });

        var buoys_markers = [];
        var redIcon = new L.Icon({
          iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png'
        });
        for (var i = 0; i < buoys_plane.length; i++){
            marker = new L.marker([buoys_plane[i][1],buoys_plane[i][2]], {icon: redIcon}).bindPopup(buoys_plane[i][0]).on('click', erase_user_marker);
            buoys_markers.push(marker);
        }
        buoys_layer = L.layerGroup(buoys_markers);

        map.addLayer(buoys_layer);
    }

    function removeAreaSelect() {
        var layers_arr = Object.values(map._layers);
        layers_arr.shift();
        $.each(layers_arr, function(i, e){e.remove()});
    }

    $('#select_app')
      .dropdown()
    ;

    $('#select_dataset')
      .dropdown()
    ;

    $('#select_variable')
      .dropdown()
    ;

    $('#select_dataset_wave_resource_assessment_single')
      .dropdown()
    ;
    $('#select_dataset_wave_resource_assessment_area')
      .dropdown()
    ;
    $('#select_dataset_data_visualisation')
      .dropdown()
    ;

     var dataset_selection = $('#select_dataset_data_visualisation :selected').val();

    $('#'+dataset_selection+'-variables').show();

    function create_new_area_select(area_select_bounds){
        $(".leaflet-interactive").remove();
        areaSelect = L.rectangle(area_select_bounds);
        map.addLayer(areaSelect);
        areaSelect.editing.enable();
        area_bounds = areaSelect.getBounds();
        areaSelect.on("edit", function() {
                area_bounds = this.getBounds();
            });
        map.fitBounds(area_select_bounds);
        bounds = [area_select_bounds[0][0],area_select_bounds[0][1],area_select_bounds[1][0],area_select_bounds[1][1]];
        $('#lat_min').val(bounds[0]);
        $('#lat_max').val(bounds[2]);
        $('#lon_min').val(bounds[1]);
        $('#lon_max').val(bounds[3]);

    }

    function erase_user_marker(){
        // alert(this.getLatLng().lat);
        $('#lat').val(this.getLatLng().lat);
        $('#lon').val(this.getLatLng().lng);
        if(user_marker != undefined){
            map.removeLayer(user_marker);
        }
    }

    $(function () {
        $('.app-selector').change(function () {

            //Wave Forecast Scenario
            if ($('.app-selector :selected').val() == "Wave_Forecast") {
                mode = "location";
                $('.dataset-selector').hide();
                $('.coverage-date-filters').show();
                $('#wave-forecast-results').show();
                $('.single-spatial-selection').show();

                map.on('click', function(e){
                    if (mode == "location") {
                        $('#lat').val(e.latlng.lat);
                        $('#lon').val(e.latlng.lng);

                        if (user_marker != undefined) {
                            map.removeLayer(user_marker);
                        }

                        user_marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup("AS4254").addTo(map);
                        single_marker_layer = L.layerGroup(user_marker);
                        map.addLayer(single_marker_layer);
                    }
                 });

                /*          Set Up Time Pickers For Start/End Date  */

                var dateToday = new  Date();
                var startpick = $('#startdatepicker').datetimepicker({
                    autoclose: true,
                    pickerPosition: 'top-left',
                    startDate: dateToday,
                    // todayBtn: true,

                }).datetimepicker("setDate", new Date());

                var endpick = $('#enddatepicker').datetimepicker({
                    autoclose: true,
                    pickerPosition: 'top-left',
                    endDate: dateToday+7
                });

                // startpick.on('changeDate', function(e){
                //     var minDate = new Date(e.date.valueOf());
                //     endpick.datetimepicker('setStartDate' ,minDate);
                //     startdate = $('#startdatepicker input').val();
                //     set_time_filters();
                // });
                //
                // endpick.on('changeDate', function(e){
                //     var maxDate = new Date(e.date.valueOf());
                //     startpick.datetimepicker('setEndDate', maxDate);
                //     enddate = $('#enddatepicker input').val();
                //     set_time_filters();
                // });

            }
            else{
                $('.single-spatial-selection').hide();
                $('.dataset-selector').show();
                $('.coverage-date-filters').show();
                $('#wave-forecast-results').hide();
                $('#startdatepicker input').val('');
                $('#enddatepicker input').val('');
                startdate = null;
                enddate =null;
            }
            if ($('.app-selector :selected').val() == "Wave_Resource_Assessment_area"){
                mode = "area";
                $('.wave_resource_assessment_area_dropdown').show();
                $('.spatial-selection').show();
                $('#wave-atlas-results').show();
                create_new_area_select([[29.2575,-24.2578],[49.479,37.0898]]);

                $('.leaflet-edit-move').mouseup(function(){
                    area_bounds = areaSelect.getBounds();
                    var swlat = Math.round(area_bounds.getSouthWest().lat * 10000) / 10000;
                    var swlon = Math.round(area_bounds.getSouthWest().lng * 10000) / 10000;
                    var nelat = Math.round(area_bounds.getNorthEast().lat * 10000) / 10000;
                    var nelon = Math.round(area_bounds.getNorthEast().lng * 10000) / 10000;
                    bounds = [swlat,swlon,nelat,nelon];
                    $('#lat_min').val(bounds[0]);
                    $('#lat_max').val(bounds[2]);
                    $('#lon_min').val(bounds[1]);
                    $('#lon_max').val(bounds[3]);
                });

                $('.leaflet-edit-resize').mouseup(function(){
                    area_bounds = areaSelect.getBounds();
                    var swlat = Math.round(area_bounds.getSouthWest().lat * 10000) / 10000;
                    var swlon = Math.round(area_bounds.getSouthWest().lng * 10000) / 10000;
                    var nelat = Math.round(area_bounds.getNorthEast().lat * 10000) / 10000;
                    var nelon = Math.round(area_bounds.getNorthEast().lng * 10000) / 10000;
                    bounds = [swlat,swlon,nelat,nelon];
                    $('#lat_min').val(bounds[0]);
                    $('#lat_max').val(bounds[2]);
                    $('#lon_min').val(bounds[1]);
                    $('#lon_max').val(bounds[3]);
                });

                $('#lat_min, #lat_max, #lon_min, #lon_max').change(function () {
                    bounds = [parseFloat($('#lat_min').val()),parseFloat($('#lon_min').val()),parseFloat($('#lat_max').val()),parseFloat($('#lon_max').val())];
                    $(".leaflet-interactive").remove();
                    create_new_area_select([[parseFloat($('#lat_min').val()),parseFloat($('#lon_min').val())],[parseFloat($('#lat_max').val()),parseFloat($('#lon_max').val())]]);
                });
            }
            else {
                mode = "location";
                $('.wave_resource_assessment_area_dropdown').hide();
                $('#wave-atlas-results').hide();
                $('.spatial-selection').hide();
                removeAreaSelect();

            }
            if ($('.app-selector :selected').val() == "Data_Visualisation"){
                $('.data_visualisation').show();
                $('.single-spatial-selection').show();
                $('#data-visualisation-results').show();
                $('.variable-selector').show();

                $('#select_dataset_data_visualisation :selected').val();
                $('#'+dataset_selection+'-variables').show();

                create_buoys_plane();

                map.on('click', function(e) {
                    if (mode == "location"){
                        $('#lat').val(e.latlng.lat);
                        $('#lon').val(e.latlng.lng);

                        if (user_marker != undefined) {
                            map.removeLayer(user_marker);
                        }

                        user_marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup("AS4254").addTo(map);
                        single_marker_layer = L.layerGroup(user_marker);
                        map.addLayer(single_marker_layer);
                    }
                 });
            }
            else{
                $('.data_visualisation').hide();
                $('#data-visualisation-results').hide();
                $('.variable-selector').hide();
                // $('.single-spatial-selection').hide();

                if(map.hasLayer(buoys_layer)) {
                    map.removeLayer(buoys_layer);
                }
            }
             if ($('.app-selector :selected').val() == "Wave_Resource_Assessment_single"){
                 $('.wave_resource_assessment_single_dropdown').show();
                 $('#wave-resource-assessment').show();
                 $('.single-spatial-selection').show();

                 map.on('click', function(e){
                    if (mode == "location") {
                        $('#lat').val(e.latlng.lat);
                        $('#lon').val(e.latlng.lng);

                        if (user_marker != undefined) {
                            map.removeLayer(user_marker);
                        }
                        user_marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup("AS4254").addTo(map);
                        single_marker_layer = L.layerGroup(user_marker);
                        map.addLayer(single_marker_layer);
                    }
                 });
            }
            else {
                    $('.wave_resource_assessment_single_dropdown').hide();
                    $('#wave-resource-assessment').hide();
             }
        })
    });

   $(function () {
       $('#select_dataset_data_visualisation').change(function () {

           $('.variables-selector').hide();
           var dataset_selection = $('#select_dataset_data_visualisation').val();
            $('#'+dataset_selection+'-variables').show();
       })
   })

});

<commit_msg>pointer cursor when marker is to be added<commit_after>

var buoys_layer;
var single_marker_layer;
var user_marker = {};
var mode=null;
$(document).ready(function() {

    function create_buoys_plane(){
        var buoys_plane = [];
        $('.buoy').each(function(i, obj) {
            var buoy_id = $(this).data("id");
            var buoy_lat = $(this).data("lat");
            var buoy_lon = $(this).data("lon");
            var buoy = [buoy_id, buoy_lat, buoy_lon];
            buoys_plane.push(buoy);
        });

        var buoys_markers = [];
        var redIcon = new L.Icon({
          iconUrl: 'https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png'
        });
        for (var i = 0; i < buoys_plane.length; i++){
            marker = new L.marker([buoys_plane[i][1],buoys_plane[i][2]], {icon: redIcon}).bindPopup(buoys_plane[i][0]).on('click', erase_user_marker);
            buoys_markers.push(marker);
        }
        buoys_layer = L.layerGroup(buoys_markers);

        map.addLayer(buoys_layer);
    }

    function removeAreaSelect() {
        var layers_arr = Object.values(map._layers);
        layers_arr.shift();
        $.each(layers_arr, function(i, e){e.remove()});
    }

    $('#select_app')
      .dropdown()
    ;

    $('#select_dataset')
      .dropdown()
    ;

    $('#select_variable')
      .dropdown()
    ;

    $('#select_dataset_wave_resource_assessment_single')
      .dropdown()
    ;
    $('#select_dataset_wave_resource_assessment_area')
      .dropdown()
    ;
    $('#select_dataset_data_visualisation')
      .dropdown()
    ;

     var dataset_selection = $('#select_dataset_data_visualisation :selected').val();

    $('#'+dataset_selection+'-variables').show();

    function create_new_area_select(area_select_bounds){
        $(".leaflet-interactive").remove();
        areaSelect = L.rectangle(area_select_bounds);
        map.addLayer(areaSelect);
        areaSelect.editing.enable();
        area_bounds = areaSelect.getBounds();
        areaSelect.on("edit", function() {
                area_bounds = this.getBounds();
            });
        map.fitBounds(area_select_bounds);
        bounds = [area_select_bounds[0][0],area_select_bounds[0][1],area_select_bounds[1][0],area_select_bounds[1][1]];
        $('#lat_min').val(bounds[0]);
        $('#lat_max').val(bounds[2]);
        $('#lon_min').val(bounds[1]);
        $('#lon_max').val(bounds[3]);

    }

    function erase_user_marker(){
        // alert(this.getLatLng().lat);
        $('#lat').val(this.getLatLng().lat);
        $('#lon').val(this.getLatLng().lng);
        if(user_marker != undefined){
            map.removeLayer(user_marker);
        }
    }

    $(function () {
        $('.app-selector').change(function () {

            //Wave Forecast Scenario
            if ($('.app-selector :selected').val() == "Wave_Forecast") {
                $('.dataset-selector').hide();
                $('.coverage-date-filters').show();
                $('#wave-forecast-results').show();
                $('.single-spatial-selection').show();

                map.on('click', function(e){
                    if (mode == "location") {
                        $('#lat').val(e.latlng.lat);
                        $('#lon').val(e.latlng.lng);

                        if (user_marker != undefined) {
                            map.removeLayer(user_marker);
                        }

                        user_marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup("AS4254").addTo(map);
                        single_marker_layer = L.layerGroup(user_marker);
                        map.addLayer(single_marker_layer);
                    }
                 });

                /*          Set Up Time Pickers For Start/End Date  */

                var dateToday = new  Date();
                var startpick = $('#startdatepicker').datetimepicker({
                    autoclose: true,
                    pickerPosition: 'top-left',
                    startDate: dateToday,
                    // todayBtn: true,

                }).datetimepicker("setDate", new Date());

                var endpick = $('#enddatepicker').datetimepicker({
                    autoclose: true,
                    pickerPosition: 'top-left',
                    endDate: dateToday+7
                });

                // startpick.on('changeDate', function(e){
                //     var minDate = new Date(e.date.valueOf());
                //     endpick.datetimepicker('setStartDate' ,minDate);
                //     startdate = $('#startdatepicker input').val();
                //     set_time_filters();
                // });
                //
                // endpick.on('changeDate', function(e){
                //     var maxDate = new Date(e.date.valueOf());
                //     startpick.datetimepicker('setEndDate', maxDate);
                //     enddate = $('#enddatepicker input').val();
                //     set_time_filters();
                // });

            }
            else{
                $('.single-spatial-selection').hide();
                $('.dataset-selector').show();
                $('.coverage-date-filters').show();
                $('#wave-forecast-results').hide();
                $('#startdatepicker input').val('');
                $('#enddatepicker input').val('');
                startdate = null;
                enddate =null;
            }
            if ($('.app-selector :selected').val() == "Wave_Resource_Assessment_area"){
                mode = "area";
                $("#map").css("cursor", "grab");
                $('.wave_resource_assessment_area_dropdown').show();
                $('.spatial-selection').show();
                $('#wave-atlas-results').show();
                create_new_area_select([[29.2575,-24.2578],[49.479,37.0898]]);

                $('.leaflet-edit-move').mouseup(function(){
                    area_bounds = areaSelect.getBounds();
                    var swlat = Math.round(area_bounds.getSouthWest().lat * 10000) / 10000;
                    var swlon = Math.round(area_bounds.getSouthWest().lng * 10000) / 10000;
                    var nelat = Math.round(area_bounds.getNorthEast().lat * 10000) / 10000;
                    var nelon = Math.round(area_bounds.getNorthEast().lng * 10000) / 10000;
                    bounds = [swlat,swlon,nelat,nelon];
                    $('#lat_min').val(bounds[0]);
                    $('#lat_max').val(bounds[2]);
                    $('#lon_min').val(bounds[1]);
                    $('#lon_max').val(bounds[3]);
                });

                $('.leaflet-edit-resize').mouseup(function(){
                    area_bounds = areaSelect.getBounds();
                    var swlat = Math.round(area_bounds.getSouthWest().lat * 10000) / 10000;
                    var swlon = Math.round(area_bounds.getSouthWest().lng * 10000) / 10000;
                    var nelat = Math.round(area_bounds.getNorthEast().lat * 10000) / 10000;
                    var nelon = Math.round(area_bounds.getNorthEast().lng * 10000) / 10000;
                    bounds = [swlat,swlon,nelat,nelon];
                    $('#lat_min').val(bounds[0]);
                    $('#lat_max').val(bounds[2]);
                    $('#lon_min').val(bounds[1]);
                    $('#lon_max').val(bounds[3]);
                });

                $('#lat_min, #lat_max, #lon_min, #lon_max').change(function () {
                    bounds = [parseFloat($('#lat_min').val()),parseFloat($('#lon_min').val()),parseFloat($('#lat_max').val()),parseFloat($('#lon_max').val())];
                    $(".leaflet-interactive").remove();
                    create_new_area_select([[parseFloat($('#lat_min').val()),parseFloat($('#lon_min').val())],[parseFloat($('#lat_max').val()),parseFloat($('#lon_max').val())]]);
                });
            }
            else {
                mode = "location";
                $("#map").css("cursor", "pointer");
                $('.wave_resource_assessment_area_dropdown').hide();
                $('#wave-atlas-results').hide();
                $('.spatial-selection').hide();
                removeAreaSelect();

            }
            if ($('.app-selector :selected').val() == "Data_Visualisation"){
                $('.data_visualisation').show();
                $('.single-spatial-selection').show();
                $('#data-visualisation-results').show();
                $('.variable-selector').show();

                $('#select_dataset_data_visualisation :selected').val();
                $('#'+dataset_selection+'-variables').show();

                create_buoys_plane();

                map.on('click', function(e) {
                    if (mode == "location"){
                        $('#lat').val(e.latlng.lat);
                        $('#lon').val(e.latlng.lng);

                        if (user_marker != undefined) {
                            map.removeLayer(user_marker);
                        }

                        user_marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup("AS4254").addTo(map);
                        single_marker_layer = L.layerGroup(user_marker);
                        map.addLayer(single_marker_layer);
                    }
                 });
            }
            else{
                $('.data_visualisation').hide();
                $('#data-visualisation-results').hide();
                $('.variable-selector').hide();
                // $('.single-spatial-selection').hide();

                if(map.hasLayer(buoys_layer)) {
                    map.removeLayer(buoys_layer);
                }
            }
             if ($('.app-selector :selected').val() == "Wave_Resource_Assessment_single"){
                 $('.wave_resource_assessment_single_dropdown').show();
                 $('#wave-resource-assessment').show();
                 $('.single-spatial-selection').show();

                 map.on('click', function(e){
                    if (mode == "location") {
                        $('#lat').val(e.latlng.lat);
                        $('#lon').val(e.latlng.lng);

                        if (user_marker != undefined) {
                            map.removeLayer(user_marker);
                        }
                        user_marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup("AS4254").addTo(map);
                        single_marker_layer = L.layerGroup(user_marker);
                        map.addLayer(single_marker_layer);
                    }
                 });
            }
            else {
                    $('.wave_resource_assessment_single_dropdown').hide();
                    $('#wave-resource-assessment').hide();
             }
        })
    });

   $(function () {
       $('#select_dataset_data_visualisation').change(function () {

           $('.variables-selector').hide();
           var dataset_selection = $('#select_dataset_data_visualisation').val();
            $('#'+dataset_selection+'-variables').show();
       })
   })

});

<|endoftext|>


<commit_before>/* Contains methods that either attach events to listen to user actions
 * or that are called due to an user action. */

/* @public
 * Attaches listener to all writable input elements and looks for
 * changes in them. If there are, an undo step is added. It also updates
 * the section/question headers, if the changed field is used in the
 * header. Only ever needs to be called once. */
FormEditor.prototype.attachChangeListenerToAllInputs = function() {
  var match = "select, input, textarea";
  $("#form_editor").on("focusin change", match, function(event) {
    if(event.type == "focusin") // not a typo, focus_in_ (or focus_out_)
      $F().fillUndoTmp();
    else {
      $F().addUndoStep("changing " + event.target.id, $F().undoTmp);
      $F().handleSectionAndQuestionUpdates($(event.target));
    }
  });
};

/* @public
 * Sets up the question and section headers with detailed info. Only
 * should be called once; after the form has loaded. */
FormEditor.prototype.initSectionAndQuestionHeaders = function() {
  // likely candidates that will be required for the header.
  var s = ".section input:visible[id*='/title']  ,";
  s += ".question input:visible[id*='/qtext']    ,";
  s += ".question input:visible[id$='/db_column']";
  $(s).each(function(ind, elm) {
    $F().handleSectionAndQuestionUpdates($(elm));
  });
};

/* @public
 * Checks if the given element is used to generate the header info. If
 * it is, the header will be updated automatically. */
FormEditor.prototype.handleSectionAndQuestionUpdates = function(elm) {
  if(!elm.is("input")) return;

  var id = elm.attr("id");
  // quick check if the element is suitable at all
  if(id.indexOf("/title") === -1 && id.indexOf("/qtext") === -1 && id.indexOf("/db_column") === -1)
    return;

  var section = elm.parents(".section");
  var title = section.find("input:visible[id*='/title']:first");
  if(id === title.attr("id")) {
    var el = section.children("h5");
    el.attr("data-title", elm.val());
    // work around webkit not updating the element even after data-attr
    // have been changed
    if($.browser.webkit) el.replaceWith(el[0].outerHTML);
    return;
  }

  var q = elm.parents(".question");
  var qtext = q.find("input:visible[id*='/qtext']:first");
  if(id === qtext.attr("id")) {
    var el = q.children("h6");
    el.attr("data-qtext", elm.val().slice(0,40));
    if($.browser.webkit) el.replaceWith(el[0].outerHTML);
    return;
  }

  var dbcol = q.find("input:visible[id$='/db_column']");
  if(id === dbcol.attr("id")) {
    var el = q.children("h6");
    el.attr("data-db-column", elm.val());
    if($.browser.webkit) el.replaceWith(el[0].outerHTML);
  }
};

/* @public
 * Attaches events to collapse/show links that actually allow collapsing
 * or showing that DOM element. Since the elements are hidden initially
 * their height is unknown and a proper slideDown animation is not
 * possible. In that case, just guess the height. Only needs to be
 * called once. */
FormEditor.prototype.attachCollapsers = function() {
  $("#form_editor").on("click", ".collapsable .header a.collapse", function(){
    var el = $(this).parents(".collapsable");
    if(el.hasClass("closed")) {
      // animate to old height first, then remove the fixed value so it
      // automatically adjusts to its contents. If the value isn’t
      // present, just guess and hope no one notices.
      el.animate({height: el.data("old-height") || "35rem"}, $F().animationSpeed, function() {
        el.removeClass("closed");
        el.attr("style", "");
        $(window).scroll(); // re-position toolbox
      });
    } else {
      el.data("old-height", el.height());
      // keep height in sync with formeditor.scss. grep this: CLOSEDHEIGHT
      el.animate({height:"3.5rem"}, $F().animationSpeed, function() {
        $(window).scroll(); // re-position toolbox
        el.addClass("closed")
      });
    }
  });
};

/* @public
 * Attaches listener to the original form tag. On submission parses the
 * form into YAML in the original textarea. */
FormEditor.prototype.attachFormSubmit = function() {
  $("body").on("submit", "form", function(ev) {
    if($(this).find("#form_content").length == 0)
      return;

    $F().dom2yaml();
  });
};

/* @public
 * Makes all text areas autosize to their content. Only needs to be
 * called once, because it listens for new text areas. */
FormEditor.prototype.attachTextAreaAutosize = function() {
  // watch for new text areas
  $('#form_editor').on("focusin", "textarea", function(ev) {
    $(this).autosize();
  });
  // areas existing initially
  $('#form_editor textarea').autosize();
};

/* @public
 * Called when the user changes type of a question. Handles showing
 * and hiding the appropriate boxes, checkmarks, etc. for that question
 * type. */
FormEditor.prototype.questionTypeChanged = function(element) {
  var path = $(element).attr("id").replace(/\/type$/, "");
  var vis = ATTRIBUTES["Visualizers"][element.value];
  this.assert(vis, "Unsupported question type: " + element.value);
  var visEl = document.getElementById(path + "/visualizer");
  var oldValue = visEl.value;
  $(visEl).empty();
  $(visEl).append(this.createOptionsForSelect(vis, oldValue));

  if(element.value == "Single") {
    this.getDomObjFromPath(path + "/hide_answers").parent().show();
    this.getDomObjFromPath(path + "/last_is_textbox").parent().show();
  } else {
    this.getDomObjFromPath(path + "/hide_answers").parent().hide();
    this.getDomObjFromPath(path + "/last_is_textbox").parent().hide();
  }

  if(element.value == "Text")
    this.getDomObjFromPath(path + "/height").parent().show();
  else
    this.getDomObjFromPath(path + "/height").parent().hide();

  if(element.value == "Tutor" || element.value == "Text")
    this.getDomObjFromPath(path + "/boxes").parent().hide();
  else
    this.getDomObjFromPath(path + "/boxes").parent().show();
};
<commit_msg>simplifiy selectors for header-updates a bit; they were selecting almost all textboxes anyway<commit_after>/* Contains methods that either attach events to listen to user actions
 * or that are called due to an user action. */

/* @public
 * Attaches listener to all writable input elements and looks for
 * changes in them. If there are, an undo step is added. It also updates
 * the section/question headers, if the changed field is used in the
 * header. Only ever needs to be called once. */
FormEditor.prototype.attachChangeListenerToAllInputs = function() {
  var match = "select, input, textarea";
  $("#form_editor").on("focusin change", match, function(event) {
    if(event.type == "focusin") // not a typo, focus_in_ (or focus_out_)
      $F().fillUndoTmp();
    else {
      $F().addUndoStep("changing " + event.target.id, $F().undoTmp);
      $F().handleSectionAndQuestionUpdates($(event.target));
    }
  });
};

/* @public
 * Sets up the question and section headers with detailed info. Only
 * should be called once; after the form has loaded. */
FormEditor.prototype.initSectionAndQuestionHeaders = function() {
  // likely candidates that will be required for the header.
  var s = "input:visible[id*='/title']  ,";
  s += "input:visible[id*='/qtext']    ,";
  s += "input:visible[id$='/db_column']";
  $(s).each(function(ind, elm) {
    $F().handleSectionAndQuestionUpdates($(elm));
  });
};

/* @public
 * Checks if the given element is used to generate the header info. If
 * it is, the header will be updated automatically. */
FormEditor.prototype.handleSectionAndQuestionUpdates = function(elm) {
  if(!elm.is("input")) return;

  var id = elm.attr("id");
  // quick check if the element is suitable at all
  if(id.indexOf("/title") === -1 && id.indexOf("/qtext") === -1 && id.indexOf("/db_column") === -1)
    return;

  var section = elm.parents(".section");
  var title = section.find("input:visible[id*='/title']:first");
  if(id === title.attr("id")) {
    var el = section.children("h5");
    el.attr("data-title", elm.val());
    // work around webkit not updating the element even after data-attr
    // have been changed
    if($.browser.webkit) el.replaceWith(el[0].outerHTML);
    return;
  }

  var q = elm.parents(".question");
  var qtext = q.find("input:visible[id*='/qtext']:first");
  if(id === qtext.attr("id")) {
    var el = q.children("h6");
    el.attr("data-qtext", elm.val().slice(0,40));
    if($.browser.webkit) el.replaceWith(el[0].outerHTML);
    return;
  }

  var dbcol = q.find("input:visible[id$='/db_column']");
  if(id === dbcol.attr("id")) {
    var el = q.children("h6");
    el.attr("data-db-column", elm.val());
    if($.browser.webkit) el.replaceWith(el[0].outerHTML);
  }
};

/* @public
 * Attaches events to collapse/show links that actually allow collapsing
 * or showing that DOM element. Since the elements are hidden initially
 * their height is unknown and a proper slideDown animation is not
 * possible. In that case, just guess the height. Only needs to be
 * called once. */
FormEditor.prototype.attachCollapsers = function() {
  $("#form_editor").on("click", ".collapsable .header a.collapse", function(){
    var el = $(this).parents(".collapsable");
    if(el.hasClass("closed")) {
      // animate to old height first, then remove the fixed value so it
      // automatically adjusts to its contents. If the value isn’t
      // present, just guess and hope no one notices.
      el.animate({height: el.data("old-height") || "35rem"}, $F().animationSpeed, function() {
        el.removeClass("closed");
        el.attr("style", "");
        $(window).scroll(); // re-position toolbox
      });
    } else {
      el.data("old-height", el.height());
      // keep height in sync with formeditor.scss. grep this: CLOSEDHEIGHT
      el.animate({height:"3.5rem"}, $F().animationSpeed, function() {
        $(window).scroll(); // re-position toolbox
        el.addClass("closed")
      });
    }
  });
};

/* @public
 * Attaches listener to the original form tag. On submission parses the
 * form into YAML in the original textarea. */
FormEditor.prototype.attachFormSubmit = function() {
  $("body").on("submit", "form", function(ev) {
    if($(this).find("#form_content").length == 0)
      return;

    $F().dom2yaml();
  });
};

/* @public
 * Makes all text areas autosize to their content. Only needs to be
 * called once, because it listens for new text areas. */
FormEditor.prototype.attachTextAreaAutosize = function() {
  // watch for new text areas
  $('#form_editor').on("focusin", "textarea", function(ev) {
    $(this).autosize();
  });
  // areas existing initially
  $('#form_editor textarea').autosize();
};

/* @public
 * Called when the user changes type of a question. Handles showing
 * and hiding the appropriate boxes, checkmarks, etc. for that question
 * type. */
FormEditor.prototype.questionTypeChanged = function(element) {
  var path = $(element).attr("id").replace(/\/type$/, "");
  var vis = ATTRIBUTES["Visualizers"][element.value];
  this.assert(vis, "Unsupported question type: " + element.value);
  var visEl = document.getElementById(path + "/visualizer");
  var oldValue = visEl.value;
  $(visEl).empty();
  $(visEl).append(this.createOptionsForSelect(vis, oldValue));

  if(element.value == "Single") {
    this.getDomObjFromPath(path + "/hide_answers").parent().show();
    this.getDomObjFromPath(path + "/last_is_textbox").parent().show();
  } else {
    this.getDomObjFromPath(path + "/hide_answers").parent().hide();
    this.getDomObjFromPath(path + "/last_is_textbox").parent().hide();
  }

  if(element.value == "Text")
    this.getDomObjFromPath(path + "/height").parent().show();
  else
    this.getDomObjFromPath(path + "/height").parent().hide();

  if(element.value == "Tutor" || element.value == "Text")
    this.getDomObjFromPath(path + "/boxes").parent().hide();
  else
    this.getDomObjFromPath(path + "/boxes").parent().show();
};
<|endoftext|>


<commit_before>define(['sprd/entity/DesignConfiguration', "sprd/util/ProductUtil", "js/core/Bindable", 'pimp/data/PimpImageService', "sprd/entity/Size", 'sprd/data/ImageUploadService', "flow", 'sprd/util/UnitUtil'], function (DesignConfiguration, ProductUtil, Bindable, PimpImageService, Size, ImageUploadService, flow, UnitUtil) {

    return DesignConfiguration.inherit('sprd.model.SpecialTextConfiguration', {

        defaults: {
            text: null,
            font: null,
            _size: Size,
            aspectRatio: 1,
            previewImageUrl: null,
            _allowScale: true,
            loading: false,
            align: null,
            initialized: false
        },

        type: "specialText",

        inject: {
            pimpImageService: PimpImageService
        },

        ctor: function () {
            this.$designCache = {};
            this.callBase();
        },

        /***
         * saves assets asynchronously
         * @param callback
         */
        save: function (callback) {

            var self = this,
                cacheId = [self.$.text, self.$.align, self.get("font.id")].join("#");

            flow()
                .seq("design", function (cb) {

                    if (self.$designCache.hasOwnProperty(cacheId)) {
                        cb(null, self.$designCache[cacheId]);
                    } else {
                        // create a full font size image
                        self.$.pimpImageService.generateDesign({
                            text: self.$.text,
                            font: self.$.font
                        }, cb);
                    }

                })
                .seq(function () {

                    var design = this.vars.design;

                    self.$designCache[cacheId] = design;
                    self.set("design", design);
                })
                .exec(callback);
        },

        _commitChangedAttributes: function ($) {
            this.callBase();

            if (!this.$.initialized) {
                return;
            }

            if (this._hasSome($, ["pimpImageService", "text", "font"])) {
                var self = this;
                var oldSize = this.$._size;
                this.fetchImage(function () {
                    self.$.offset.set('x', self.$.offset.$.x + 0.5 * self.$.scale.x * (oldSize.$.width - self.$._size.$.width));
                });
            }
        },

        fetchImage: function (callback) {
            var self = this,
                text = this.$.text,
                font = this.$.font,
                pimpImageService = this.$.pimpImageService;

            if (pimpImageService && text && font) {
                this.set('loading', true);
                pimpImageService.generateImage({
                    text: text,
                    size: "M",
                    font: font
                }, function (err, data) {
                    if (!err) {

                        var width = (parseInt(data.width) || 1) * 4,
                            height = (parseInt(data.height) || 1) * 4;

                        var size = UnitUtil.convertSizeToMm(new Size({width: width, height: height, unit: "px"}), self.$.printType.$.dpi);

                        self.set({
                            "previewImageUrl": (data || {}).src,
                            "_size": size
                        });
                    } else {
                        self.set('previewImageUrl', null);
                    }

                    self.set('loading', false);
                    callback && callback(err);
                });
            }
        },

        init: function (callback) {

            this.synchronizeFunctionCall(function (callback) {

                var self = this;

                flow()
                    .seq(function (cb) {
                        DesignConfiguration.prototype.init.call(self, cb);
                    })
                    .seq(function () {
                        var printType = self.$.printType,
                            design = self.$.design;

                        if (design) {

                            var split = design.$.name.split(";");
                            self.set({
                                font: {
                                    $: {
                                        id: split[1]
                                    }
                                },
                                align: split
                            }, {
                                silent: true
                            });

                            if (design.$.size && printType && printType.$.dpi) {
                                var dpi = printType.$.dpi;
                                self.set("_size", UnitUtil.convertSizeToMm(design.$.size, dpi), {
                                    silent: true
                                });
                            }
                        }
                    })
                    .seq(function (cb) {
                        self.fetchImage(function () {
                            cb();
                        });
                    })
                    .exec(function (err) {
                        self.set("initialized", true);
                        callback(err);
                    });

            }, "init", callback, this);

        },

        height: function (scale) {
            return this.callBase(scale);
        }.onChange("_size"),

        width: function (scale) {
            return this.callBase(scale);
        }.onChange("_size"),

        size: function () {
            return this.$._size;
        }.onChange("_size"),

        getPossiblePrintTypes: function (appearance) {
            var ret = [],
                printArea = this.$.printArea,
                design = this.$.design;

            if (printArea && appearance && design) {
                ret = ProductUtil.getPossiblePrintTypesForSpecialText(printArea, appearance.$.id);
            }

            return ret;
        }

            .
            onChange("printArea"),

        getSizeForPrintType: function (printType) {
            if (printType && printType.$.dpi) {
                var dpi = printType.$.dpi;
                return UnitUtil.convertSizeToMm(this.$._size, dpi);
            }

            return Size.empty;
        },

        isAllowedOnPrintArea: function (printArea) {
            return printArea && printArea.get("restrictions.designAllowed") == true &&
                printArea.get("restrictions.textAllowed") == true;
        },

        getPossiblePrintTypesForPrintArea: function (printArea, appearanceId) {
            return ProductUtil.getPossiblePrintTypesForSpecialText(printArea, appearanceId);
        },

        minimumScale: function () {
            // TODO:
            return this.callBase();
        }
    });
});<commit_msg>debounced textarea input and removed submit button<commit_after>define(['sprd/entity/DesignConfiguration', "sprd/util/ProductUtil", "js/core/Bindable", 'pimp/data/PimpImageService', "sprd/entity/Size", 'sprd/data/ImageUploadService', "flow", 'sprd/util/UnitUtil'], function (DesignConfiguration, ProductUtil, Bindable, PimpImageService, Size, ImageUploadService, flow, UnitUtil) {

    return DesignConfiguration.inherit('sprd.model.SpecialTextConfiguration', {

        defaults: {
            text: null,
            font: null,
            _size: Size,
            aspectRatio: 1,
            previewImageUrl: null,
            _allowScale: true,
            loading: false,
            align: null,
            initialized: false
        },

        type: "specialText",

        inject: {
            pimpImageService: PimpImageService
        },

        ctor: function () {
            this.$designCache = {};
            this.callBase();
        },

        /***
         * saves assets asynchronously
         * @param callback
         */
        save: function (callback) {

            var self = this,
                cacheId = [self.$.text, self.$.align, self.get("font.id")].join("#");

            flow()
                .seq("design", function (cb) {

                    if (self.$designCache.hasOwnProperty(cacheId)) {
                        cb(null, self.$designCache[cacheId]);
                    } else {
                        // create a full font size image
                        self.$.pimpImageService.generateDesign({
                            text: self.$.text,
                            font: self.$.font
                        }, cb);
                    }

                })
                .seq(function () {

                    var design = this.vars.design;

                    self.$designCache[cacheId] = design;
                    self.set("design", design);
                })
                .exec(callback);
        },

        _commitChangedAttributes: function ($) {
            this.callBase();

            if (!this.$.initialized) {
                return;
            }

            if (this._hasSome($, ["pimpImageService", "text", "font"])) {
                this._debounceFunctionCall(this.fetchImage, "fetchImage", 200, this, [], "DELAY");
            }
        },

        fetchImage: function (callback) {
            var self = this,
                text = this.$.text,
                font = this.$.font,
                pimpImageService = this.$.pimpImageService;

            if (pimpImageService && text && font) {
                var oldSize = this.$._size;
                this.set('loading', true);
                if (this.$lastListener) {
                    this.$lastListener.cancelled = true;
                }

                var listener = {
                    cancelled: false
                };

                var cb = function (err, data) {
                    if (listener.cancelled) {
                        return;
                    }

                    if (!err) {

                        var width = (parseInt(data.width) || 1) * 4,
                            height = (parseInt(data.height) || 1) * 4;

                        var size = UnitUtil.convertSizeToMm(new Size({width: width, height: height, unit: "px"}), self.$.printType.$.dpi);

                        self.set({
                            "previewImageUrl": (data || {}).src,
                            "_size": size
                        });
                    } else {
                        self.set('previewImageUrl', null);
                    }
                    self.$.offset.set('x', self.$.offset.$.x + 0.5 * self.$.scale.x * (oldSize.$.width - self.$._size.$.width));

                    self.set('loading', false);
                    callback && callback(err);
                };

                this.$lastListener = listener;

                pimpImageService.generateImage({
                    text: text,
                    size: "M",
                    font: font
                }, cb);
            }
        },

        init: function (callback) {

            this.synchronizeFunctionCall(function (callback) {

                var self = this;

                flow()
                    .seq(function (cb) {
                        DesignConfiguration.prototype.init.call(self, cb);
                    })
                    .seq(function () {
                        var printType = self.$.printType,
                            design = self.$.design;

                        if (design) {

                            var split = design.$.name.split(";");
                            self.set({
                                font: {
                                    $: {
                                        id: split[1]
                                    }
                                },
                                align: split
                            }, {
                                silent: true
                            });

                            if (design.$.size && printType && printType.$.dpi) {
                                var dpi = printType.$.dpi;
                                self.set("_size", UnitUtil.convertSizeToMm(design.$.size, dpi), {
                                    silent: true
                                });
                            }
                        }
                    })
                    .seq(function (cb) {
                        self.fetchImage(function () {
                            cb();
                        });
                    })
                    .exec(function (err) {
                        self.set("initialized", true);
                        callback(err);
                    });

            }, "init", callback, this);

        },

        height: function (scale) {
            return this.callBase(scale);
        }
            .
            onChange("_size"),

        width: function (scale) {
            return this.callBase(scale);
        }

            .
            onChange("_size"),

        size: function () {
            return this.$._size;
        }

            .
            onChange("_size"),

        getPossiblePrintTypes: function (appearance) {
            var ret = [],
                printArea = this.$.printArea,
                design = this.$.design;

            if (printArea && appearance && design) {
                ret = ProductUtil.getPossiblePrintTypesForSpecialText(printArea, appearance.$.id);
            }

            return ret;
        }

            .
            onChange("printArea"),

        getSizeForPrintType: function (printType) {
            if (printType && printType.$.dpi) {
                var dpi = printType.$.dpi;
                return UnitUtil.convertSizeToMm(this.$._size, dpi);
            }

            return Size.empty;
        },

        isAllowedOnPrintArea: function (printArea) {
            return printArea && printArea.get("restrictions.designAllowed") == true &&
                printArea.get("restrictions.textAllowed") == true;
        },

        getPossiblePrintTypesForPrintArea: function (printArea, appearanceId) {
            return ProductUtil.getPossiblePrintTypesForSpecialText(printArea, appearanceId);
        },

        minimumScale: function () {
            // TODO:
            return this.callBase();
        }
    });
})
;<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';
import SelectBar from 'ui/components/new/SelectBar';
import Select from 'ui/components/new/common/Select';
import Tabs from 'ui/components/new/common/Tabs';
import stopwatchIcon from 'ui/assets/images/stopwatch@2x.png';
import closeIcon from 'ui/assets/images/close@2x.png';
import settingsIcon from 'ui/assets/images/settings.svg';

const Container = styled.div`
  flex-grow: 1;
`;

const Controls = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px;
`;

const SettingsBar = styled.div`
  border-top: 1px solid #f0f0f0;
  padding: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const TextEditor = styled.div`
  border-top: 1px solid #f0f0f0;
  padding: 6px;
`;

const Icon = styled.img`
  height: 16px;
  user-select: none;
  align-self: center;
  cursor: pointer;
`;

const Input = styled.input`
  border: none;
  background-color: #f0f0f0;
  border-radius: 4px;
  flex-grow: 1;
  height: 24px;
  outline: 0;
  font-size: 14px;
  padding: 0 6px;
`;

const Actions = styled.div`
  display: flex;
  align-items: center;
`;

const TeamSync = styled.div`
`;

const ImportExport = styled.div`
`;

const delayPreset = [
  { value: 500, label: '0.5s' },
  { value: 1000, label: '1s' },
  { value: 2000, label: '2s' },
  { value: 5000, label: '5s' }
];

const contentTypeHeaderToString = (headers) => {
  if (!headers || !headers['content-type']) {
    return null;
  }

  const contentType = headers['content-type'];

  switch (true) {
    case contentType.match('application/json'):
      return 'JSON';

    case contentType.match('text/xml'):
      return 'XML';

    case contentType.match('text/html'):
      return 'HTML';

    case contentType.match('text/plain'):
      return 'Plain text';

    case contentType.match('multipart'):
      return 'File';

    default:
      return null;
  }
};

class Editor extends React.Component {
  constructor() {
    super();

    this.state = {
      selectedTab: 'response',
      selectedResponseContentTab: 'body'
    };

    this.selectTab                = this.selectTab.bind(this);
    this.selectResponseContentTab = this.selectResponseContentTab.bind(this);
  }

  selectTab(selectedTab) {
    this.setState({ selectedTab });
  }

  selectResponseContentTab(selectedResponseContentTab) {
    this.setState({ selectedResponseContentTab });
  }

  render() {
    const { selectedMock } = this.props;

    if (!selectedMock) {
      return
Please select mock
;
    }

    return (
      <Container>
        <Controls>
          <Tabs options={ ['request', 'response'] }
                selectedTab={ this.state.selectedTab }
                selectTab={ this.selectTab }/>

          <Actions>
            <TeamSync>
              Team Sync
            </TeamSync>

            <ImportExport>
              Import & Export
            </ImportExport>

            <Icon src={ settingsIcon } alt="Settings"/>
            <Icon src={ closeIcon } alt="Close" onClick={ this.props.onClose }/>
          </Actions>
        </Controls>

        {
          this.state.selectedTab === 'response' &&
          <SettingsBar>
            <Actions>
              <SelectBar values={[200, 201, 401, 500]}
                         other={ true }
                         selectedValue={ selectedMock.response.status }/>

              <SelectBar values={['JSON', 'XML', 'HTML', 'Plain text', 'File']}
                         selectedValue={ contentTypeHeaderToString(selectedMock.response.headers) }/>

              <Select
                valueIcon={ stopwatchIcon }
                value={ selectedMock.response.delay }
                options={ delayPreset.concat({
                  value: selectedMock.response.delay,
                  label: selectedMock.response.delay + 'ms'
                }) }/>
            </Actions>

            <Tabs options={ ['headers', 'body'] }
                  selectTab={ this.selectResponseContentTab }
                  selectedTab={ this.state.selectedResponseContentTab }/>
          </SettingsBar>
        }

        {
          this.state.selectedTab === 'request' &&
          <SettingsBar>
            <SelectBar values={['GET', 'POST', 'PUT', 'DELETE']}
                       selectedValue={ selectedMock.method }/>

            <Input type="text" value={ selectedMock.url }/>
          </SettingsBar>
        }

        <TextEditor>
          { JSON.stringify(selectedMock.response.body) }
        </TextEditor>
      </Container>
    );
  }
}

export default Editor;
<commit_msg>show the right data in text editor<commit_after>import React from 'react';
import styled from 'styled-components';
import SelectBar from 'ui/components/new/SelectBar';
import Select from 'ui/components/new/common/Select';
import Tabs from 'ui/components/new/common/Tabs';
import stopwatchIcon from 'ui/assets/images/stopwatch@2x.png';
import closeIcon from 'ui/assets/images/close@2x.png';
import settingsIcon from 'ui/assets/images/settings.svg';

const Container = styled.div`
  flex-grow: 1;
`;

const Controls = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px;
`;

const SettingsBar = styled.div`
  border-top: 1px solid #f0f0f0;
  padding: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const TextEditor = styled.div`
  border-top: 1px solid #f0f0f0;
  padding: 6px;
`;

const Icon = styled.img`
  height: 16px;
  user-select: none;
  align-self: center;
  cursor: pointer;
`;

const Input = styled.input`
  border: none;
  background-color: #f0f0f0;
  border-radius: 4px;
  flex-grow: 1;
  height: 24px;
  outline: 0;
  font-size: 14px;
  padding: 0 6px;
`;

const Actions = styled.div`
  display: flex;
  align-items: center;
`;

const TeamSync = styled.div`
`;

const ImportExport = styled.div`
`;

const delayPreset = [
  { value: 500, label: '0.5s' },
  { value: 1000, label: '1s' },
  { value: 2000, label: '2s' },
  { value: 5000, label: '5s' }
];

const contentTypeHeaderToString = (headers) => {
  if (!headers || !headers['content-type']) {
    return null;
  }

  const contentType = headers['content-type'];

  switch (true) {
    case contentType.match('application/json'):
      return 'JSON';

    case contentType.match('text/xml'):
      return 'XML';

    case contentType.match('text/html'):
      return 'HTML';

    case contentType.match('text/plain'):
      return 'Plain text';

    case contentType.match('multipart'):
      return 'File';

    default:
      return null;
  }
};

class Editor extends React.Component {
  constructor() {
    super();

    this.state = {
      selectedTab: 'response',
      selectedResponseContentTab: 'body'
    };

    this.selectTab                = this.selectTab.bind(this);
    this.selectResponseContentTab = this.selectResponseContentTab.bind(this);
  }

  selectTab(selectedTab) {
    this.setState({ selectedTab });
  }

  selectResponseContentTab(selectedResponseContentTab) {
    this.setState({ selectedResponseContentTab });
  }

  render() {
    const { selectedMock } = this.props;

    if (!selectedMock) {
      return
Please select mock
;
    }

    return (
      <Container>
        <Controls>
          <Tabs options={ ['request', 'response'] }
                selectedTab={ this.state.selectedTab }
                selectTab={ this.selectTab }/>

          <Actions>
            <TeamSync>
              Team Sync
            </TeamSync>

            <ImportExport>
              Import & Export
            </ImportExport>

            <Icon src={ settingsIcon } alt="Settings"/>
            <Icon src={ closeIcon } alt="Close" onClick={ this.props.onClose }/>
          </Actions>
        </Controls>

        {
          this.state.selectedTab === 'response' &&
          <SettingsBar>
            <Actions>
              <SelectBar values={[200, 201, 401, 500]}
                         other={ true }
                         selectedValue={ selectedMock.response.status }/>

              <SelectBar values={['JSON', 'XML', 'HTML', 'Plain text', 'File']}
                         selectedValue={ contentTypeHeaderToString(selectedMock.response.headers) }/>

              <Select
                valueIcon={ stopwatchIcon }
                value={ selectedMock.response.delay }
                options={ delayPreset.concat({
                  value: selectedMock.response.delay,
                  label: selectedMock.response.delay + 'ms'
                }) }/>
            </Actions>

            <Tabs options={ ['headers', 'body'] }
                  selectTab={ this.selectResponseContentTab }
                  selectedTab={ this.state.selectedResponseContentTab }/>
          </SettingsBar>
        }

        {
          this.state.selectedTab === 'request' &&
          <SettingsBar>
            <SelectBar values={['GET', 'POST', 'PUT', 'DELETE']}
                       selectedValue={ selectedMock.method }/>

            <Input type="text" value={ selectedMock.url }/>
          </SettingsBar>
        }

        <TextEditor>
          { this.state.selectedTab === 'request' &&
            JSON.stringify(selectedMock.params) }

          { this.state.selectedTab === 'response' &&
            this.state.selectedResponseContentTab === 'body' &&
            JSON.stringify(selectedMock.response.body) }

          { this.state.selectedTab === 'response' &&
            this.state.selectedResponseContentTab === 'headers' &&
            JSON.stringify(selectedMock.response.headers) }
        </TextEditor>
      </Container>
    );
  }
}

export default Editor;
<|endoftext|>


<commit_before>$('.table#applications_table').bootstrapTable({
  onClickRow: function (row, $element) {
    window.location.href = "../../application_state?applicationId=" + row.id;
  }
});

$(document).ready(function() {
    $("#file").change(function() {
        $("#fileName").text(new Option($('input[type=file]')[0].files[0].name).innerHTML);
    });

});

function CandidateCreateModel(){
    var self = this;

    ko.bindingHandlers.valueWithInit = {
        init: function(element, valueAccessor, allBindingsAccessor, data) {
            var property = valueAccessor(),
                value = element.value;

            //create the observable, if it doesn't exist
            if (!ko.isWriteableObservable(data[property])) {
                data[property] = ko.observable();
            }

            data[property](value);

            ko.applyBindingsToNode(element, { value: data[property] });
        }
    };

    ko.bindingHandlers.initDisplay = {
        init: function(element, valueAccessor, allBindingsAccessor, data) {
            self.modify(true);
        }
    };

    function sendCandidateWithAjax(url, method) {
        return $.ajax({
                   url: url,
                   method: method,
                   contentType: 'application/json',
                   dataType: "json",
                   data: JSON.stringify({
                       id: self.id(),
                       name: self.name(),
                       referer: self.referer(),
                       email: self.email(),
                       languageSkill: self.languageSkill(),
                       phone: self.phone(),
                       description: self.description(),
                       cvFilename: self.cvFilename()
                   })
               });
    }

    function sendFileWithAjax(url, formData) {
        return $.ajax({
                   url: url,
                   data: formData,
                   type: 'POST',
                   contentType: false,
                   processData: false,
               });
    }

    self.ajaxCall = function() {
        var candidateValidationUrl = '/atsy/secure/candidate/validate';
        var candidateUrl = '/atsy/secure/candidate';
        var fileValidationUrl = '/atsy/secure/fileUpload/validate';
        var fileUploadUrl = '/atsy/secure/fileUpload/candidate/';

        var form = $("#candidate-create-form");
        var formData = new FormData();

        if(($('input[type=file]'))[0] != undefined) {
            formData.append('file', $('input[type=file]')[0].files[0]);
        }

        // Send candidate to validate
        sendCandidateWithAjax(candidateValidationUrl, form.attr('method')).done(function (xhr) {
            // If candidate is valid, then hide the error msg
            self.showError(false);
            if (($('input[type=file]')[0] === undefined) || ($('input[type=file]').val() === '')) {
                // Send candidate to save
                sendCandidateWithAjax(candidateUrl, form.attr('method')).done(function (xhr) {
                    // If there is no error with candidate, then hide the error msg
                    self.showError(false);
                    window.location = form.attr('action')+ '/' + xhr.id;
                    // If there is error with candidate, then show the error msg
                }).error(function (xhr) {
                    self.candidateErrorResponse(xhr.responseJSON);
                    self.showError(true);
                });
             // If the file exists
            } else {
                // If file exists, then send file to validate
                sendFileWithAjax(fileValidationUrl, formData).done(function (xhr) {
                    // If file is valid, then hide the error msg
                    self.showFileError(false);
                    // Send candidate to save or update
                    sendCandidateWithAjax(candidateUrl, form.attr('method')).done(function (xhr) {
                        // If there is no error with candidate, then hide the error msg
                        self.showError(false);
                        // Send file to save
                        sendFileWithAjax(fileUploadUrl + xhr.id, formData).done(function (xhr) {
                            // If there is no error with file, then hide error msg
                            self.showFileError(false);
                            // If candidate and file are corrects
                            window.location = form.attr('action')+ '/' + xhr.id;
                        }).error(function (xhr) {
                            // If there is error with file, then show the error msg
                            self.fileErrorResponse(xhr.responseJSON);
                            self.showFileError(true);
                        });
                    // If there is error with candidate, then show the error msg
                    }).error(function (xhr) {
                        self.candidateErrorResponse(xhr.responseJSON);
                        self.showError(true);
                    });
                // If file is not valid, then show the error msg
                }).error(function (xhr) {
                    self.fileErrorResponse(xhr.responseJSON);
                    self.showFileError(true);
                });
            }
        // If candidate is not valid, then show error msg
        }).error(function (xhr) {
            self.candidateErrorResponse(xhr.responseJSON);
            self.showError(true);
            // If the file exists
            if (($('input[type=file]')[0] != undefined) && ($('input[type=file]').val() != '')) {
                // Send file to save
                sendFileWithAjax(fileValidationUrl, formData).done(function (xhr) {
                    // If there is no error with file, then hide the error msg
                    self.showFileError(false);
                // If file is not valid, then show the error msg
                }).error(function (xhr) {
                    self.fileErrorResponse(xhr.responseJSON);
                    self.showFileError(true);
                });
            }
        });
    }

    self.candidateErrorResponse = ko.observable(null);
    self.fileErrorResponse = ko.observable(null);
    self.showError = ko.observable(false);
    self.showFileError = ko.observable(false);

    self.errorMessage = ko.pureComputed(function() {
      if (self.candidateErrorResponse() === null) {
        return ""
      }

      return self.candidateErrorResponse().errorMessage;
    });

    self.fileErrorMessage = ko.pureComputed(function() {
        if (self.fileErrorResponse() === null) {
            return "";
        }

        return self.fileErrorResponse().errorMessage;
    });

    self.fieldMessages = ko.pureComputed(function() {
        if (self.candidateErrorResponse() === null) {
          return [];
        }

        return Object.keys(self.candidateErrorResponse().fields).map(function(key) {
            return self.candidateErrorResponse().fields[key];
        });
    });

    self.modify = ko.observable(false);

    self.modify_display_true = function() {
        self.modify(true);
        self.showError(false);
        self.showFileError(false);
        $("#candidate-create-form").validator('destroy');
        candidateModel.id(savedModel.id);
        candidateModel.name(savedModel.name);
        candidateModel.referer(savedModel.referer);
        candidateModel.email(savedModel.email);
        candidateModel.languageSkill(savedModel.languageSkill);
        candidateModel.phone(savedModel.phone);
        $("#fileName").text('');
    };

    self.modify_display_false = function() {
        self.modify(false);
        savedModel = ko.toJS(candidateModel);
    };

     $("#downloadLink").on('click', function (event) {
         var url = $(this).data('file');

         event.preventDefault();
         event.stopPropagation();

         $.ajax({
             url: url,
             type: 'GET'
         }).done(function (xhr) {
            var downloadUrl = "/atsy/secure/fileDownload/" + xhr.id;
            window.location = downloadUrl;
         }).error(function (xhr) {
             self.fileErrorResponse(xhr.responseJSON);
             self.showFileError(true);
         });
     });
}

var savedModel;

var candidateModel = new CandidateCreateModel();

$('#candidate-create-form').validator().on('submit', function (e) {
  if (e.isDefaultPrevented()) {
    // handle the invalid form...
  } else {
    candidateModel.ajaxCall();
    return false;
  }
});

ko.applyBindings(candidateModel);

function creationDateFormatter(value, row, index) {
    var dateTime = new Date(row.creationDate);
    return dateTimeFormatter(dateTime);
}

function modificationDateFormatter(value, row, index) {
    var dateTime = new Date(row.modificationDate);
    return dateTimeFormatter(dateTime);
}

function dateTimeFormatter(dateTime) {
    var options = {year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric'};
    return dateTime.toLocaleDateString('hu-HU', options);
}

function actionFormatter(value, row, index) {
    return [
        '',
        '',
        '',
    ].join('');
}

window.channelsEvents = {
    'click .remove': function (e, value, row) {
         var container = $('#applications_table').parent();
         var options = getOptions('question.delete.application.js', 'selected.element.not.found', row, container, '../../applications');
         e.stopImmediatePropagation();
         bootbox.dialog(options);
    }
};
<commit_msg>trim candidate's name before saving<commit_after>$('.table#applications_table').bootstrapTable({
  onClickRow: function (row, $element) {
    window.location.href = "../../application_state?applicationId=" + row.id;
  }
});

$(document).ready(function() {
    $("#file").change(function() {
        $("#fileName").text(new Option($('input[type=file]')[0].files[0].name).innerHTML);
    });

});

function CandidateCreateModel(){
    var self = this;

    ko.bindingHandlers.valueWithInit = {
        init: function(element, valueAccessor, allBindingsAccessor, data) {
            var property = valueAccessor(),
                value = element.value;

            //create the observable, if it doesn't exist
            if (!ko.isWriteableObservable(data[property])) {
                data[property] = ko.observable();
            }

            data[property](value);

            ko.applyBindingsToNode(element, { value: data[property] });
        }
    };

    ko.bindingHandlers.initDisplay = {
        init: function(element, valueAccessor, allBindingsAccessor, data) {
            self.modify(true);
        }
    };

    function sendCandidateWithAjax(url, method) {
        return $.ajax({
                   url: url,
                   method: method,
                   contentType: 'application/json',
                   dataType: "json",
                   data: JSON.stringify({
                       id: self.id(),
                       name: self.name().trim(),
                       referer: self.referer(),
                       email: self.email(),
                       languageSkill: self.languageSkill(),
                       phone: self.phone(),
                       description: self.description(),
                       cvFilename: self.cvFilename()
                   })
               });
    }

    function sendFileWithAjax(url, formData) {
        return $.ajax({
                   url: url,
                   data: formData,
                   type: 'POST',
                   contentType: false,
                   processData: false,
               });
    }

    self.ajaxCall = function() {
        var candidateValidationUrl = '/atsy/secure/candidate/validate';
        var candidateUrl = '/atsy/secure/candidate';
        var fileValidationUrl = '/atsy/secure/fileUpload/validate';
        var fileUploadUrl = '/atsy/secure/fileUpload/candidate/';

        var form = $("#candidate-create-form");
        var formData = new FormData();

        if(($('input[type=file]'))[0] != undefined) {
            formData.append('file', $('input[type=file]')[0].files[0]);
        }

        // Send candidate to validate
        sendCandidateWithAjax(candidateValidationUrl, form.attr('method')).done(function (xhr) {
            // If candidate is valid, then hide the error msg
            self.showError(false);
            if (($('input[type=file]')[0] === undefined) || ($('input[type=file]').val() === '')) {
                // Send candidate to save
                sendCandidateWithAjax(candidateUrl, form.attr('method')).done(function (xhr) {
                    // If there is no error with candidate, then hide the error msg
                    self.showError(false);
                    window.location = form.attr('action')+ '/' + xhr.id;
                    // If there is error with candidate, then show the error msg
                }).error(function (xhr) {
                    self.candidateErrorResponse(xhr.responseJSON);
                    self.showError(true);
                });
             // If the file exists
            } else {
                // If file exists, then send file to validate
                sendFileWithAjax(fileValidationUrl, formData).done(function (xhr) {
                    // If file is valid, then hide the error msg
                    self.showFileError(false);
                    // Send candidate to save or update
                    sendCandidateWithAjax(candidateUrl, form.attr('method')).done(function (xhr) {
                        // If there is no error with candidate, then hide the error msg
                        self.showError(false);
                        // Send file to save
                        sendFileWithAjax(fileUploadUrl + xhr.id, formData).done(function (xhr) {
                            // If there is no error with file, then hide error msg
                            self.showFileError(false);
                            // If candidate and file are corrects
                            window.location = form.attr('action')+ '/' + xhr.id;
                        }).error(function (xhr) {
                            // If there is error with file, then show the error msg
                            self.fileErrorResponse(xhr.responseJSON);
                            self.showFileError(true);
                        });
                    // If there is error with candidate, then show the error msg
                    }).error(function (xhr) {
                        self.candidateErrorResponse(xhr.responseJSON);
                        self.showError(true);
                    });
                // If file is not valid, then show the error msg
                }).error(function (xhr) {
                    self.fileErrorResponse(xhr.responseJSON);
                    self.showFileError(true);
                });
            }
        // If candidate is not valid, then show error msg
        }).error(function (xhr) {
            self.candidateErrorResponse(xhr.responseJSON);
            self.showError(true);
            // If the file exists
            if (($('input[type=file]')[0] != undefined) && ($('input[type=file]').val() != '')) {
                // Send file to save
                sendFileWithAjax(fileValidationUrl, formData).done(function (xhr) {
                    // If there is no error with file, then hide the error msg
                    self.showFileError(false);
                // If file is not valid, then show the error msg
                }).error(function (xhr) {
                    self.fileErrorResponse(xhr.responseJSON);
                    self.showFileError(true);
                });
            }
        });
    }

    self.candidateErrorResponse = ko.observable(null);
    self.fileErrorResponse = ko.observable(null);
    self.showError = ko.observable(false);
    self.showFileError = ko.observable(false);

    self.errorMessage = ko.pureComputed(function() {
      if (self.candidateErrorResponse() === null) {
        return ""
      }

      return self.candidateErrorResponse().errorMessage;
    });

    self.fileErrorMessage = ko.pureComputed(function() {
        if (self.fileErrorResponse() === null) {
            return "";
        }

        return self.fileErrorResponse().errorMessage;
    });

    self.fieldMessages = ko.pureComputed(function() {
        if (self.candidateErrorResponse() === null) {
          return [];
        }

        return Object.keys(self.candidateErrorResponse().fields).map(function(key) {
            return self.candidateErrorResponse().fields[key];
        });
    });

    self.modify = ko.observable(false);

    self.modify_display_true = function() {
        self.modify(true);
        self.showError(false);
        self.showFileError(false);
        $("#candidate-create-form").validator('destroy');
        candidateModel.id(savedModel.id);
        candidateModel.name(savedModel.name);
        candidateModel.referer(savedModel.referer);
        candidateModel.email(savedModel.email);
        candidateModel.languageSkill(savedModel.languageSkill);
        candidateModel.phone(savedModel.phone);
        $("#fileName").text('');
    };

    self.modify_display_false = function() {
        self.modify(false);
        savedModel = ko.toJS(candidateModel);
    };

     $("#downloadLink").on('click', function (event) {
         var url = $(this).data('file');

         event.preventDefault();
         event.stopPropagation();

         $.ajax({
             url: url,
             type: 'GET'
         }).done(function (xhr) {
            var downloadUrl = "/atsy/secure/fileDownload/" + xhr.id;
            window.location = downloadUrl;
         }).error(function (xhr) {
             self.fileErrorResponse(xhr.responseJSON);
             self.showFileError(true);
         });
     });
}

var savedModel;

var candidateModel = new CandidateCreateModel();

$('#candidate-create-form').validator().on('submit', function (e) {
  if (e.isDefaultPrevented()) {
    // handle the invalid form...
  } else {
    candidateModel.ajaxCall();
    return false;
  }
});

ko.applyBindings(candidateModel);

function creationDateFormatter(value, row, index) {
    var dateTime = new Date(row.creationDate);
    return dateTimeFormatter(dateTime);
}

function modificationDateFormatter(value, row, index) {
    var dateTime = new Date(row.modificationDate);
    return dateTimeFormatter(dateTime);
}

function dateTimeFormatter(dateTime) {
    var options = {year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric'};
    return dateTime.toLocaleDateString('hu-HU', options);
}

function actionFormatter(value, row, index) {
    return [
        '',
        '',
        '',
    ].join('');
}

window.channelsEvents = {
    'click .remove': function (e, value, row) {
         var container = $('#applications_table').parent();
         var options = getOptions('question.delete.application.js', 'selected.element.not.found', row, container, '../../applications');
         e.stopImmediatePropagation();
         bootbox.dialog(options);
    }
};
<|endoftext|>


<commit_before>const common = require( './common' ),
	vscode = require( 'vscode' ),
	CHAR_TYPE = common.CHAR_TYPE,
	STRATEGIES = {
		CAMEL_CASE: 1,
		SAME_CASE: 2
	},
	regExpMapping = common.regExpMapping,
	regExpExcludeMapping = common.regExpExcludeMapping;

module.exports = {
	moveRight( textEditor ) {
		let sel = textEditor.selections[ 0 ],
			newPos = this._movePositionRight( textEditor.document, sel.active );

		if ( newPos ) {
			// Update the selection.
			textEditor.selection = new vscode.Selection( newPos, newPos );
		}
	},

	/**
	 * Expands (or shrinks depending where range's active position is) the selection to the right side of text.
	 *
	 * @param {TextEditor} textEditor
	 */
	selectRight( textEditor ) {
		let sel = textEditor.selections[ 0 ],
			newPos = this._movePositionRight( textEditor.document, sel.active ),
			newSel = new vscode.Selection( sel.anchor, newPos );

		if ( newSel ) {
			// Update the selection.
			textEditor.selection = newSel;
		}
	},

	moveLeft( textEditor ) {},

	_moveSelectionRight( doc, sel ) {
		let end = !sel.isReversed ? sel.end : sel.start,
			anchor = !sel.isReversed ? sel.start : sel.end,
			lineText = doc.lineAt( end ).text,
			// The text after the selection.
			textAhead = lineText.substr( end.character ),
			lastChar = end.character > 0 ? lineText.substr( end.character - 1, 1 ) : ' ';

		return new vscode.Selection( anchor, end.with( end.line, end.character + 1 ) );
	},

	_movePositionRight( doc, position ) {
		let lineText = doc.lineAt( position ).text,
			// The text after the selection.
			textAhead = lineText.substr( position.character ),
			lastCharType = this._getCharType( position.character > 0 ? lineText.substr( position.character - 1, 1 ) : ' ' ),
			endLine = position.line,
			curCharType = this._getCharType( textAhead[ 0 ] ),
			endPos = null;

		if ( curCharType !== lastCharType ) {
			// Handles cases like:
			// is^CorrectColor
			// isC^orrectColor
			// is ^correct
			// is^ correct
			let farAheadCharType = this._getCharType( textAhead[ 1 ] );

			if ( curCharType !== farAheadCharType ) {
				// Case 1 above, caret is before the first capitalized letter in camel case.
				// Note we're skipping first char (capitalized letter), and because of that we're adding 1.
				endPos = position.character + textAhead.substr( 1 ).search( regExpExcludeMapping[ farAheadCharType ] ) + 1;
			}
		}

		if ( endPos === null ) {
			endPos = position.character + textAhead.search( regExpExcludeMapping[ curCharType ] );
		}

		return new vscode.Position( position.line, endPos );
	},

	/**
	 * Tells the character type based on `char`.
	 *
	 * @param {String} char A character to be tested.
	 * @returns {Number} A value based on `CHAR_TYPE` members.
	 */
	_getCharType( char ) {
		char = String( char )[ 0 ] || '';

		for ( let typeValue in regExpMapping ) {
			if ( char.match( regExpMapping[ typeValue ] ) ) {
				return Number( typeValue );
			}
		}

		return CHAR_TYPE.OTHER;
	}
};<commit_msg>Removed old leftovers.<commit_after>const common = require( './common' ),
	vscode = require( 'vscode' ),
	CHAR_TYPE = common.CHAR_TYPE,
	STRATEGIES = {
		CAMEL_CASE: 1,
		SAME_CASE: 2
	},
	regExpMapping = common.regExpMapping,
	regExpExcludeMapping = common.regExpExcludeMapping;

module.exports = {
	moveRight( textEditor ) {
		let sel = textEditor.selections[ 0 ],
			newPos = this._movePositionRight( textEditor.document, sel.active );

		if ( newPos ) {
			// Update the selection.
			textEditor.selection = new vscode.Selection( newPos, newPos );
		}
	},

	/**
	 * Expands (or shrinks depending where range's active position is) the selection to the right side of text.
	 *
	 * @param {TextEditor} textEditor
	 */
	selectRight( textEditor ) {
		let sel = textEditor.selections[ 0 ],
			newPos = this._movePositionRight( textEditor.document, sel.active ),
			newSel = new vscode.Selection( sel.anchor, newPos );

		if ( newSel ) {
			// Update the selection.
			textEditor.selection = newSel;
		}
	},

	moveLeft( textEditor ) {},

	_movePositionRight( doc, position ) {
		let lineText = doc.lineAt( position ).text,
			// The text after the selection.
			textAhead = lineText.substr( position.character ),
			lastCharType = this._getCharType( position.character > 0 ? lineText.substr( position.character - 1, 1 ) : ' ' ),
			endLine = position.line,
			curCharType = this._getCharType( textAhead[ 0 ] ),
			endPos = null;

		if ( curCharType !== lastCharType ) {
			// Handles cases like:
			// is^CorrectColor
			// isC^orrectColor
			// is ^correct
			// is^ correct
			let farAheadCharType = this._getCharType( textAhead[ 1 ] );

			if ( curCharType !== farAheadCharType ) {
				// Case 1 above, caret is before the first capitalized letter in camel case.
				// Note we're skipping first char (capitalized letter), and because of that we're adding 1.
				endPos = position.character + textAhead.substr( 1 ).search( regExpExcludeMapping[ farAheadCharType ] ) + 1;
			}
		}

		if ( endPos === null ) {
			endPos = position.character + textAhead.search( regExpExcludeMapping[ curCharType ] );
		}

		return new vscode.Position( position.line, endPos );
	},

	/**
	 * Tells the character type based on `char`.
	 *
	 * @param {String} char A character to be tested.
	 * @returns {Number} A value based on `CHAR_TYPE` members.
	 */
	_getCharType( char ) {
		char = String( char )[ 0 ] || '';

		for ( let typeValue in regExpMapping ) {
			if ( char.match( regExpMapping[ typeValue ] ) ) {
				return Number( typeValue );
			}
		}

		return CHAR_TYPE.OTHER;
	}
};<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import OrthologyTable from './orthologyTable';

const caseInsensitiveCompare = (stringA, stringB) => {
  const stringALowerCase = stringA.toLowerCase();
  const stringBLowerCase = stringB.toLowerCase();
  if (stringALowerCase < stringBLowerCase) {
    return -1;
  } else if (stringALowerCase > stringBLowerCase) {
    return 1;
  } else {
    return 0;
  }
};

class OrthologyFilteredTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filterScoreGreaterThan: 0,
      filterMethod: null,
      filterBest: false,
      filterReverseBest: false,
      filterSpecies: null,
      filterConfidence: true
    };
  }

  isHighConfidence(dat) {
    return (
      dat.predictionMethodsMatched === 'ZFIN' ||
      dat.predictionMethodsMatched === 'HGNC' ||
      dat.predictionMethodsMatched.length > 2 ||
      (dat.predictionMethodsMatched.length === 2 && dat.isBestRevScore)
    )
  }

  filterCallback(dat) {
    const meetMethodFilter = this.state.filterMethod ?
      dat.predictionMethodsMatched.indexOf(this.state.filterMethod) > -1 :
      true;
    return (
      meetMethodFilter &&
      dat.predictionMethodsMatched.length > this.state.filterScoreGreaterThan &&
      (this.state.filterBest ? dat.isBestScore : true) &&
      (this.state.filterReverseBest ? dat.isBestRevScore : true) &&
      (this.state.filterSpecies ? dat.gene2SpeciesName === this.state.filterSpecies : true) &&
      (this.state.filterConfidence ? this.isHighConfidence(dat) : true)
    );
  }

  updateFilterMethod(event) {
    this.setState({
      filterMethod: event.target.value === 'all' ? null : event.target.value
    });
  }

  updateBestScoreFilter(event) {
    this.setState({
      filterBest: event.target.checked
    });
  }

  updateBestReverseScoreFilter(event) {
    this.setState({
      filterReverseBest: event.target.checked
    });
  }

  updateFilterScoreGreaterThan(event) {
    this.setState({
      filterScoreGreaterThan: event.target.value
    });
  }

  updateFilterSpecies(event) {
    this.setState({
      filterSpecies: event.target.value === 'all' ? null : event.target.value
    })
  }

  updateFilterConfidence(event) {
    this.setState({
      filterConfidence: event.target.checked
    })
  }

  render() {
    const filteredData = this.props.data.filter((dat) => this.filterCallback(dat));
    const all_methods = this.props.data[0].predictionMethodsMatched.concat(
      this.props.data[0].predictionMethodsNotCalled,
      this.props.data[0].predictionMethodsNotMatched
    ).sort(caseInsensitiveCompare);
    return (

            Best Score Only:
            <input
              checked={this.state.filterBest}
              onChange={(event) => this.updateBestScoreFilter(event)}
              type="checkbox"
            />

            Best Reverse Score Only:
            <input
              checked={this.state.filterReverseBest}
              onChange={(event) => this.updateBestReverseScoreFilter(event)}
              type="checkbox"
            />

            Exclude low confidence matches:
            <input
              checked={this.state.filterConfidence}
              onChange={(event) => this.updateFilterConfidence(event)}
              type="checkbox"
            />

            Score:
            <select
              onChange={(event) => this.updateFilterScoreGreaterThan(event)}
              value={this.state.filterScoreGreaterThan}
            >
              <option value={0}>> 0</option>
              {
                all_methods.map((method, index) => {
                  const scoreGreaterThanValue = index + 1;
                  return <option value={scoreGreaterThanValue}>> {scoreGreaterThanValue}</option>;
                })
              }
            </select>

            Species:
            <select
              onChange={(event) => this.updateFilterSpecies(event)}
              value={this.state.filterSpecies}
            >
              <option value="all">All</option>
              {
                this.props.data.reduce((all_species, dat) => {
                  if (all_species.indexOf(dat.gene2SpeciesName) === -1) {
                    return all_species.concat([dat.gene2SpeciesName]);
                  } else {
                    return all_species;
                  }
                }, []).map((species) => (
                  <option value={species}>{species}</option>
                ))
              }
            </select>

            Methods:
            <select
              onChange={(event) => this.updateFilterMethod(event)}
              value={this.state.filterMethod}
            >
              <option value="all">All</option>
              {
                all_methods.map((method) => (
                  <option key={method} value={method}>{method}</option>
                ))
              }
            </select>

        <OrthologyTable data={filteredData} />

    );
  }
}

OrthologyFilteredTable.propTypes = {
  // filterScoreGreaterThan: PropTypes.number,
  // filterMethods: PropTypes.string,
  // filterBest: PropTypes.bool,
  // filterReverseBest: PropTypes.bool
  data: PropTypes.arrayOf(
    PropTypes.shape({
      gene2AgrPrimaryId: PropTypes.string,
      gene2Symbol: PropTypes.string,
      gene2Species: PropTypes.number,
      gene2SpeciesName: PropTypes.string,
      predictionMethodsMatched: PropTypes.arrayOf(PropTypes.string),
      predictionMethodsNotCalled: PropTypes.arrayOf(PropTypes.string),
      predictionMethodsNotMatched: PropTypes.arrayOf(PropTypes.string),
      isBestScore: PropTypes.bool,
      isBestRevScore: PropTypes.bool,
    })
  )
};

export default OrthologyFilteredTable;
<commit_msg>style labels<commit_after>import React, { Component, PropTypes } from 'react';
import OrthologyTable from './orthologyTable';

const caseInsensitiveCompare = (stringA, stringB) => {
  const stringALowerCase = stringA.toLowerCase();
  const stringBLowerCase = stringB.toLowerCase();
  if (stringALowerCase < stringBLowerCase) {
    return -1;
  } else if (stringALowerCase > stringBLowerCase) {
    return 1;
  } else {
    return 0;
  }
};

class OrthologyFilteredTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filterScoreGreaterThan: 0,
      filterMethod: null,
      filterBest: false,
      filterReverseBest: false,
      filterSpecies: null,
      filterConfidence: true
    };
  }

  isHighConfidence(dat) {
    return (
      dat.predictionMethodsMatched === 'ZFIN' ||
      dat.predictionMethodsMatched === 'HGNC' ||
      dat.predictionMethodsMatched.length > 2 ||
      (dat.predictionMethodsMatched.length === 2 && dat.isBestRevScore)
    )
  }

  filterCallback(dat) {
    const meetMethodFilter = this.state.filterMethod ?
      dat.predictionMethodsMatched.indexOf(this.state.filterMethod) > -1 :
      true;
    return (
      meetMethodFilter &&
      dat.predictionMethodsMatched.length > this.state.filterScoreGreaterThan &&
      (this.state.filterBest ? dat.isBestScore : true) &&
      (this.state.filterReverseBest ? dat.isBestRevScore : true) &&
      (this.state.filterSpecies ? dat.gene2SpeciesName === this.state.filterSpecies : true) &&
      (this.state.filterConfidence ? this.isHighConfidence(dat) : true)
    );
  }

  updateFilterMethod(event) {
    this.setState({
      filterMethod: event.target.value === 'all' ? null : event.target.value
    });
  }

  updateBestScoreFilter(event) {
    this.setState({
      filterBest: event.target.checked
    });
  }

  updateBestReverseScoreFilter(event) {
    this.setState({
      filterReverseBest: event.target.checked
    });
  }

  updateFilterScoreGreaterThan(event) {
    this.setState({
      filterScoreGreaterThan: event.target.value
    });
  }

  updateFilterSpecies(event) {
    this.setState({
      filterSpecies: event.target.value === 'all' ? null : event.target.value
    })
  }

  updateFilterConfidence(event) {
    this.setState({
      filterConfidence: event.target.checked
    })
  }

  render() {
    const filteredData = this.props.data.filter((dat) => this.filterCallback(dat));
    const all_methods = this.props.data[0].predictionMethodsMatched.concat(
      this.props.data[0].predictionMethodsNotCalled,
      this.props.data[0].predictionMethodsNotMatched
    ).sort(caseInsensitiveCompare);

    const labelStyle = {
      margin: '0 1em 1em 0',
    };
    const inputStyle = {
      margin: '0 0.5em'
    };

    return (

            Best Score Only:
            <input
              checked={this.state.filterBest}
              onChange={(event) => this.updateBestScoreFilter(event)}
              style={inputStyle}
              type="checkbox"
            />

            Best Reverse Score Only:
            <input
              checked={this.state.filterReverseBest}
              onChange={(event) => this.updateBestReverseScoreFilter(event)}
              style={inputStyle}
              type="checkbox"
            />

            Exclude low confidence matches:
            <input
              checked={this.state.filterConfidence}
              onChange={(event) => this.updateFilterConfidence(event)}
              style={inputStyle}
              type="checkbox"
            />

            Score:
            <select
              onChange={(event) => this.updateFilterScoreGreaterThan(event)}
              style={inputStyle}
              value={this.state.filterScoreGreaterThan}
            >
              <option value={0}>> 0</option>
              {
                all_methods.map((method, index) => {
                  const scoreGreaterThanValue = index + 1;
                  return <option value={scoreGreaterThanValue}>> {scoreGreaterThanValue}</option>;
                })
              }
            </select>

            Species:
            <select
              onChange={(event) => this.updateFilterSpecies(event)}
              style={inputStyle}
              value={this.state.filterSpecies}
            >
              <option value="all">All</option>
              {
                this.props.data.reduce((all_species, dat) => {
                  if (all_species.indexOf(dat.gene2SpeciesName) === -1) {
                    return all_species.concat([dat.gene2SpeciesName]);
                  } else {
                    return all_species;
                  }
                }, []).map((species) => (
                  <option value={species}>{species}</option>
                ))
              }
            </select>

            Methods:
            <select
              onChange={(event) => this.updateFilterMethod(event)}
              style={inputStyle}
              value={this.state.filterMethod}
            >
              <option value="all">All</option>
              {
                all_methods.map((method) => (
                  <option key={method} value={method}>{method}</option>
                ))
              }
            </select>

        <OrthologyTable data={filteredData} />

    );
  }
}

OrthologyFilteredTable.propTypes = {
  // filterScoreGreaterThan: PropTypes.number,
  // filterMethods: PropTypes.string,
  // filterBest: PropTypes.bool,
  // filterReverseBest: PropTypes.bool
  data: PropTypes.arrayOf(
    PropTypes.shape({
      gene2AgrPrimaryId: PropTypes.string,
      gene2Symbol: PropTypes.string,
      gene2Species: PropTypes.number,
      gene2SpeciesName: PropTypes.string,
      predictionMethodsMatched: PropTypes.arrayOf(PropTypes.string),
      predictionMethodsNotCalled: PropTypes.arrayOf(PropTypes.string),
      predictionMethodsNotMatched: PropTypes.arrayOf(PropTypes.string),
      isBestScore: PropTypes.bool,
      isBestRevScore: PropTypes.bool,
    })
  )
};

export default OrthologyFilteredTable;
<|endoftext|>